ManagementObjectCollection没有实现索引器,不过是你可以你,如果你正在使用LINQ,但谁使用.NET 3或更早版本(比如我仍然怪才FirstOrDefault扩展功能在1.1上工作)可以使用以下代码,它是从任何集合实现的IEnumerable接口获取第一项的标准方式。
private ManagementObject GetItem(ManagementObjectCollection collection, int index)
{
//TODO: do null handling
IEnumerator enumerator = collection.GetEnumerator();
int currentIndex = 0;
while (enumerator.MoveNext())
{
if (currentIndex == index)
{
return enumerator.Current as ManagementObject;
}
currentIndex++;
}
throw new ArgumentOutOfRangeException("Index out of range");
}
OR
private ManagementObject GetItem(ManagementObjectCollection collection, int index)
{
//TODO: do null handling
int currentIndex = 0;
foreach (ManagementObject mo in collection)
{
if (currentIndex == index)
{
return mo;
}
currentIndex++;
}
throw new ArgumentOutOfRangeException("Index out of range");
}
我需要添加'OfType' ...'的ManagementObject月= queryCollection.OfType <
以下是两种不同的方式从任何索引检索的ManagementObject ManagementObject>()。First();' – 2014-11-14 03:21:12
我没有在'ManagementObject'中看到FirstOrDefault(),只有'OfType()。FirstOrDefault()'为我工作 –
Jack
2016-04-25 19:30:15
对于任何和我一样困惑,在这个答案中有一个错字。它应该为:ManagementObject mo = queryCollection.OfType()。FirstOrDefault()' –
SGS
2017-06-01 14:58:11