3

What's the easiest way to convert a BindingList<T> to a T[] ?

EDIT: I'm on 3.0 for this project, so no LINQ.

Gerrie Schenck
  • 22,148
  • 20
  • 68
  • 95
  • Aside: you can still use LINQ with .NET 3.0, as long as you have the C# 3.0 compiler (or VS2008). Just reference LINQBridge. – Marc Gravell Mar 06 '09 at 11:43

3 Answers3

9

Well, if you have LINQ (C# 3.0 + either .NET 3.5 or LINQBridge) you can use .ToArray() - otherwise, just create an array and copy the data.

T[] arr = new T[list.Count];
list.CopyTo(arr, 0);
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
3

In .Net 2 you have to use .CopyTo() method on your BindingList<T>

Grzenio
  • 35,875
  • 47
  • 158
  • 240
1

I've changed this post since I noticed you tagged this with .net2.0. You could use a List since it has an ToArray() method.

public T[] ToArray<T>(BindingList<T> bindingList) {
    if (bindingList == null)
        return new T[0];

    var list = new List<T>(bindingList);
    return list.ToArray();
}

Note: This is indeed a less performant solution than the CopyTo solution that other members have shown. Use their solution instead, this one creates two arrays, the result and one internal to the List instance.

sisve
  • 19,501
  • 3
  • 53
  • 95
  • The question is tagged .net2.0 – annakata Mar 06 '09 at 11:13
  • @annakata; *strictly* speaking, it is more relevant whether it is C# 2.0 or C# 3.0, as LINQ is still available with .NET 2.0 + C# 3.0 + a few fairly simple methods etc (or just LINQBridge). – Marc Gravell Mar 06 '09 at 11:16
  • @Tant102 - I preferred your original answer ;-p The List approach is a bit overkill and (for large data, at least) a bit inefficient. – Marc Gravell Mar 06 '09 at 11:17