I have list of Guid's
List<Gui开发者_StackOverflow社区d> MyList;
I need to copy its contents to Array
Guid[]
Please recommend me a pretty solution
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();
You should just have to call MyList.ToArray() to get an array of the elements.
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;
}
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).
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).
精彩评论