2010-08-27 10 views
5

Estoy tratando de acceder a ManagementObjects en ManagementObjectCollection sin utilizar una instrucción foreach, tal vez me falta algo, pero no sé cómo hacerlo, tengo que hacer algo como lo siguiente :C# Acceso a los objetos de gestión en ManagementObjectCollection

ManagementObjectSearcher query = new ManagementObjectSearcher(
    "select Name, CurrentClockSpeed from Win32_Processor"); 

ManagementObjectCollection queryCollection = query.Get(); 

ManagementObject mo = queryCollection[0]; 

Respuesta

3

ManagementObjectCollection implementa IEnumerable o ICollection, así que o debe iterar vía IEnumerable (es decir foreach) o CopyTo una matriz a través de ICollection.

Sin embargo, ya que soporta IEnumerable puede utilizar LINQ: se requiere

ManagementObject mo = queryCollection.OfType<ManagementObject>().FirstOrDefault() 

OfType<ManagementObject> porque ManagementObjectCollection apoya IEnumerable pero no IEnumerable of T.

+1

que necesitaba para agregar '' OfType' ... mo ManagementObject = queryCollection.OfType < ManagementObject>(). First(); ' –

+1

No veo' FirstOrDefault() 'en' ManagementObject', solo 'OfType (). FirstOrDefault()' funcionó para mí – Jack

+0

Para cualquier persona que está tan confundido como yo, hay un error tipográfico en esta respuesta. Debería leer: 'ManagementObject mo = queryCollection.OfType (). FirstOrDefault()' – SGS

0

Probablemente se esté perdiendo el reparto: (. Y como tal no tiene un indexador mecanografiada)

ManagementObject mo = (ManagementObject)queryCollection[0]; 

... que no creo ManagementObjectCollection es genérico

+0

-1 para el error de dirección, no se puede acceder a ManagementObjectCollection con indexación de matriz. Aquí hay una captura de pantalla de mi error: https://i.imgur.com/FBVXeA2.png – Katianie

3

No se puede llama directamente a linq desde ManagementObjectCollection (ni a un indexador entero). Hay que echarlo a IEnumerable primera:

var queryCollection = from ManagementObject x in query.Get() 
         select x; 

var manObj = queryCollection.FirstOrDefault(); 
1

ManagementObjectCollection no implementa controladores paso a paso, pero sí se puede que la función de extensión FirstOrDefault si está utilizando LINQ, pero los frikis que están utilizando .NET 3 o anterior (como yo todavía trabajando en 1.1) puede usar el siguiente código, es la forma estándar de obtener el primer elemento de cualquier colección implementada en la interfaz IEnumerable.

//TODO: Do the Null and Count Check before following lines 
IEnumerator enumerator = collection.GetEnumerator(); 
enumerator.MoveNext(); 
ManagementObject mo = (ManagementObject)enumerator.Current; 

siguientes son dos maneras diferentes para recuperar ManagementObject de cualquier índice

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"); 
} 

O

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"); 
} 
Cuestiones relacionadas