How to copy List to Array

孤人 提交于 2019-12-07 01:26:25

问题


I have list of Guid's

List<Guid> MyList;

I need to copy its contents to Array

Guid[]

Please recommend me a pretty solution


回答1:


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



回答2:


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




回答3:


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



回答4:


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




回答5:


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



来源:https://stackoverflow.com/questions/1921701/how-to-copy-list-to-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!