Search code examples
c#foreachwmi

Get all non null properties from all objects in a ManagementObjectCollection


I'm trying to simplify these two foreach loops but I cant seem to get it. it uses the management library which gets information about the OS, there's about 30 different items but I just want one. At the moment I'm scrolling through them all and display the one I want when it pops up.

try
{
    ManagementClass Management = new ManagementClass("Win32_OperatingSystem");

    foreach (ManagementObject Object in Management.GetInstances())
    {
        foreach (PropertyData Data in Object.Properties)
        {
            if (Data.Name.Equals("CSName")  && (Data.Value != null))
            {
                TxtBody.Text += "<br><font color = red>" + Data.Name + ": " + Data.Value + "</font>";
            }
        }
    }
}

Surely I can just put something like TxtBody.text += Management.PropertyData.CSName ?


Solution

  • You need at least one loop but to avoid the use of nested loops you can use LINQ.

    You could use LINQ like this:

    foreach (PropertyData Data in Management.GetInstances()
                                  .SelectMany(Object => Object.Properties
                                  .Where(Data => Data.Name.Equals("CSName") 
                                  && (Data.Value != null))))
    {
         TxtBody.Text += "<br><font color = red>" + Data.Name + ": " + Data.Value + "</font>";
    }