Fastest Convert from Collection to List<T>

匿名 (未验证) 提交于 2019-12-03 02:44:02

问题:

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


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