ManagementObjectCollection не реализует индексаторы, но да, вы можете использовать функцию расширения FirstOrDefault, если вы используете linq, но гики, которые используют .net 3 или более раннюю версию (как я все еще работаю над 1.1), могут использовать следующий код, это стандартный способ Для получения первого элемента из любой коллекции реализован интерфейс IEnumerable.
//TODO: Do the Null and Count Check before following lines
IEnumerator enumerator = collection.GetEnumerator();
enumerator.MoveNext();
ManagementObject mo = (ManagementObject)enumerator.Current;
Ниже приведены два различных способа получения ManagementObject из любого индекса
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");
}
ИЛИ
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");
}