Fastest Convert from Collection to List<T>
C#CollectionsC# Problem Overview
What I'd like to avoid:
ManagementClass m = new ManagementClass("Win32_LogicalDisk");
ManagementObjectCollection managementObjects = m.GetInstances();
List<ManagementObject> managementList = new List<ManagementObject>();
foreach(ManagementObject m in managementObjects){
managementList.Add(m);
}
Isn't there a way to get that collection into a List that looks something like:
List<ManagementObject> managementList = new List<ManagementObjec>(collection_array);
C# Solutions
Solution 1 - C#
What version of the framework? With 3.5 you could presumably use:
List<ManagementObject> managementList = managementObjects.Cast<ManagementObject>().ToList();
(edited to remove simpler version; I checked and ManagementObjectCollection
only implements the non-generic IEnumerable
form)
Solution 2 - C#
You could use
using System.Linq;
That will give you a ToList<> extension method for ICollection<>
Solution 3 - C#
managementObjects.Cast<ManagementBaseObject>().ToList();
is a good choice.
You could improve performance by pre-initialising the list capacity:
public static class Helpers
{
public static List<T> CollectionToList<T>(this System.Collections.ICollection other)
{
var output = new List<T>(other.Count);
output.AddRange(other.Cast<T>());
return output;
}
}
Solution 4 - C#
Since 3.5, anything inherited from System.Collection.IEnumerable has the convenient extension method OfType available.
If your collection is from ICollection or IEnumerable, you can just do this:
List<ManagementObject> managementList = ManagementObjectCollection.OfType<ManagementObject>().ToList();
Can't find any way simpler. : )
Solution 5 - C#
You could try:
List<ManagementObject> managementList = new List<ManagementObject>(managementObjects.ToArray());
Not sure if .ToArray() is available for the collection. If you do use the code you posted, make sure you initialize the List with the number of existing elements:
List<ManagementObject> managementList = new List<ManagementObject>(managementObjects.Count); // or .Length
Solution 6 - C#
As long as ManagementObjectCollection implements IEnumerable<ManagementObject> you can do:
List<ManagementObject> managementList = new List<ManagementObjec>(managementObjects);
If it doesn't, then you are stuck doing it the way that you are doing it.
Solution 7 - C#
you can convert like below code snippet
Collection<A> obj=new Collection<return ListRetunAPI()>