Search code examples
c#linqwmi

LINQ join query on two data sources is throwing error


I want to get the WMI values for some of the attributes mentioned in the local IList. I'm doing a WMI query and getting all the attribute values in PropertyData[] by getting the values out of queryObj.Proerties.

I'm preparing a Inner join Linq query as I'm interested in only the property name in my locally created list but it is throwing NullrefernceException. Dies the Linq query doesn't work on array or I need to initialize this PropertData object in Linq query before accessing this object property for comparision?

Please help me on this as I found this very weird and wasted lot of time on this. Following is the code snippet:

    IDictionary<string, IList<string>> biosWmiAttributes = new Dictionary<string, IList<string>>();
                    biosWmiAttributes["Win32_BIOS"] = new List<string>{"Availability",
                                                            "BatteryStatus",
                                                            "Description",
                                                            "DeviceID",
                                                            "EstimatedRunTime",
                                                            "Name",
                                                            "Status",
                                                            "PowerManagementSupported"};

     ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_BIOS");
foreach (ManagementObject queryObj in searcher.Get())
{
                            bios = new Dictionary<string, string>();

                            StringBuilder biosCharacteristics = new StringBuilder();
                            PropertyData[] wmiAttributes = new PropertyData[100];
                            queryObj.Properties.CopyTo(wmiAttributes, 0);

var some = from biosAttribute in biosWmiAttributes["Win32_BIOS"]
                                   join wmiAttribute in wmiAttributes on biosAttribute equals wmiAttribute.Name into biosAttributes
                                   select new {Name=biosAttributes};
}

Solution

  • PropertyData[] wmiAttributes = new PropertyData[100];
    queryObj.Properties.CopyTo(wmiAttributes, 0);
    

    Here is the problem, you're allocating 100 elements in array where actual size will not be 100. When Linq query tries to access your array you get the NullReferenceException. Change it to the following:

    PropertyData[] wmiAttributes = queryObj.Properties
                                           .Cast<PropertyData>()
                                           .ToArray();
    

    Also take a look at What is a NullReferenceException, and how do I fix it? to learn more.