views:

10122

answers:

5

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

Thanks much!

+1  A: 

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
steffenj
No, there is no .ToArray()
Marc Gravell
+5  A: 

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)

Marc Gravell
Your cast could fail, you need ManagementBaseObject instead.
mancaus
Not if we want to create a List<ManagementObject>, we don't. Perhaps OfType<ManagementObject> would be a reasonable compromise?
Marc Gravell
A: 

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.

MagicKat
The problem is: it doesn't; it only implements ICollection, IEnumerable, IDisposable
Marc Gravell
@Marc Gravell: Then he is stuck doing it the way that he is doing it. The IEnumerable<T> ctor is doing the same thing basically anyways.
MagicKat
Not with .NET 3.5, he isn't.
Marc Gravell
But we don't know which framework he is using.
MagicKat
A: 

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;
        }
    }
mancaus
In reality, pre-initializing the capacity won't save you a huge amount of time. The list will grow with a doubling strategy, so it won't have to resize many times. Less code to maintain, too.
Marc Gravell
(especially when compared to the overheads of IEnumeable, and Cast's iterator block...)
Marc Gravell
A: 

you can convert like below code snippet Collection obj=new Collection