views:

378

answers:

5

Hi

I have list of Guid's

List<Guid> MyList;

I need to copy its contents to Array

Guid[]

Please recommend me a pretty solution

+15  A: 

As Luke said in comments, the particular List<T> type already has a ToArray() method. But if you're using C# 3.0, you can leverage the ToArray() extension method on any IEnumerable instance (that includes IList, IList<T>, collections, other arrays, etc.)

var myList = new List<Guid> {Guid.NewGuid(), Guid.NewGuid()};
Guid[] array = myList.ToArray(); // instance method

IList<Guid> myList2 = new List<Guid> {Guid.NewGuid(), Guid.NewGuid()};
Guid[] array2 = myList2.ToArray(); // extension method

var myList3 = new Collection<Guid> {Guid.NewGuid(), Guid.NewGuid()};
Guid[] array3 = myList3.ToArray(); // extension method

Regarding your second question:

You can use the Select method to perform the needed projection:

var list = new List<MyClass> {new MyClass(), new MyClass()};
Guid[] array = list.Select(mc => mc.value).ToArray();
Romain Verdier
Muchas gracias.
Captain Comic
`List<T>` has it's own (ie, not an extension) `ToArray` method, available since .NET2. (Exactly the same syntax as above, although you wouldn't be able to use `var` or object initialisers without C#3.)
LukeH
@Luke: Very good point! I updated my answer accordingly. Thanks.
Romain Verdier
+9  A: 

You should just have to call MyList.ToArray() to get an array of the elements.

Adam Gritt
+3  A: 

Using the Enumerable.ToArray() Extension Method you can do:

var guidArray = MyList.ToArray();

If you're still using C# 2.0 you can use the List.ToArray method. The syntax is the same (except there's no var keyword in C# 2.0).

Winston Smith
+5  A: 

The new way (using extensions or the ToArray() method on generic lists in .Net 2.0):

Guid[] guidArray = MyList.ToArray();

The old way:

Guid[] guidArray = new guidArray[MyList.Length];
int idx = 0;
foreach (var guid in MyList)
{
    guidArray[idx++] = guid;
}
tvanfosson
C# 2.0 has `List.ToArray`, which uses `System.Array.Copy`
Winston Smith
I guess I'm showing my age. :-)
tvanfosson
A: 

Yet another option, in addition to Guid[] MyArray = MyList.ToArray():

Guid[] MyArray = new Guid[MyList.Count]; // or wherever you get your array from
MyList.CopyTo(MyArray, 0);

This solution might be better if, for whatever reason, you already have a properly-sized array and simply want to populate it (rather than construct a new one, as List<T>.ToArray() does).

Dan Tao