Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy List to Array

I have list of Guid's

List<Guid> MyList;

I need to copy its contents to Array

Guid[]

Please recommend me a pretty solution

like image 674
Captain Comic Avatar asked Dec 17 '09 13:12

Captain Comic


2 Answers

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();
like image 59
Romain Verdier Avatar answered Oct 04 '22 01:10

Romain Verdier


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

like image 25
Adam Gritt Avatar answered Oct 04 '22 01:10

Adam Gritt