Gerrie Schenck
Gerrie Schenck

Reputation: 22368

Convert a BindingList<T> to an array of T

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.

Upvotes: 3

Views: 6152

Answers (3)

sisve
sisve

Reputation: 19781

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.

Upvotes: 1

Marc Gravell
Marc Gravell

Reputation: 1063013

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);

Upvotes: 9

Grzenio
Grzenio

Reputation: 36649

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

Upvotes: 3

Related Questions