【问题标题】:LINQ join query on two data sources is throwing error [duplicate]两个数据源上的 LINQ 连接查询引发错误 [重复]
【发布时间】:2014-08-05 07:28:18
【问题描述】:

我想获取本地 IList 中提到的某些属性的 WMI 值。我正在执行 WMI 查询并通过从 queryObj.Proerties 中获取值来获取 PropertyData[] 中的所有属性值。

我正在准备 Inner join Linq 查询,因为我只对本地创建的列表中的属性名称感兴趣,但它正在抛出 NullrefernceException。死了 Linq 查询在数组上不起作用还是我需要在 Linq 查询中初始化这个 PropertData 对象,然后才能访问这个对象属性进行比较?

请帮助我,因为我发现这很奇怪并且浪费了很多时间。 以下是代码sn-p:

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

【问题讨论】:

  • 它在哪里抛出错误?是否检查了所涉及的对象是否为非空/
  • 在“wmiAttributes”数组中,我看到 PropertyData 类型的条目正确存在并且具有值。但是当我尝试在 linq 查询中访问此数组中元素的任何属性时,Obect Reference Not Set错误来了。因此,我希望从该 PropertyData[] 中获取本地列表中存在的字符串的属性值。你能提供linq查询吗?
  • 我不认为它与已经问过的任何空引用异常问题重复,因为正确的答案是数组中存在垃圾值,必须按照该问题的答案中所述进行动态初始化。所有问题都不属于“NullReferenceException”类型的共同保护伞。

标签: c# linq wmi


【解决方案1】:
PropertyData[] wmiAttributes = new PropertyData[100];
queryObj.Properties.CopyTo(wmiAttributes, 0);

这是问题所在,您在数组中分配 100 元素,实际大小不会是 100。当 Linq 查询尝试访问您的数组时,您会得到 NullReferenceException。 将其更改为以下内容:

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

还可以查看What is a NullReferenceException, and how do I fix it? 了解更多信息。

【讨论】:

  • 你是对的,因为这个任务只有“NullrefernceException”来了。谢谢 Sriram,我会将此标记为答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-15
  • 2019-11-09
  • 1970-01-01
  • 2018-10-14
  • 2023-03-19
相关资源
最近更新 更多