I'm trying to access ManagementObjects in ManagementObjectCollection without using a foreach statement, maybe I'm missing something but I can't figure out how to do it, I need to do something like the following:
开发者_如何学运维ManagementObjectSearcher query = new ManagementObjectSearcher(
"select Name, CurrentClockSpeed from Win32_Processor");
ManagementObjectCollection queryCollection = query.Get();
ManagementObject mo = queryCollection[0];
ManagementObjectCollection implements IEnumerable or ICollection, so either you must iterate it via IEnumerable (ie foreach) or CopyTo an array via ICollection.
However since it supports IEnumerable you can use Linq :
ManagementObject mo = queryCollection.OfType<ManagementObject>().FirstOrDefault()
OfType<ManagementObject>
is required because ManagementObjectCollection supports IEnumerable but not IEnumerable of T.
You can not directly call linq from ManagementObjectCollection (nor an integer indexer). You have to cast it to IEnumerable first:
var queryCollection = from ManagementObject x in query.Get()
select x;
var manObj = queryCollection.FirstOrDefault();
ManagementObjectCollection does not implements Indexers, but yes you can you FirstOrDefault extension function if you are using linq but geeks who are using .net 3 or earlier (like me still working on 1.1) can use following code, it is standard way of getting first item from any collection implemented IEnumerable interface.
//TODO: Do the Null and Count Check before following lines
IEnumerator enumerator = collection.GetEnumerator();
enumerator.MoveNext();
ManagementObject mo = (ManagementObject)enumerator.Current;
following are two different ways to retrieve ManagementObject from any index
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");
}
精彩评论