可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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);
回答1:
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)
回答2:
You could use
using System.Linq;
That will give you a ToList<> extension method for ICollection<>
回答3:
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; } }
回答4:
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
回答5:
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.
回答6:
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. : )
回答7:
you can convert like below code snippet
Collection<A> obj=new Collection<return ListRetunAPI()>