按linq查询结果异常问题分组

时间:2014-04-01 05:46:34

标签: c# linq

我正在尝试按结果分组并将检查设为null,但是在.Any().Count()someDocs上抛出错误是在内存集合中

var devices = someDocs.SelectMany(x => x.Devices).GroupBy(x => x.type);

if (devices != null && devices.Count()>0) // Exception : Object not set to instance of Object 
{
   //my code 
}

如何检查分组结果是否为空?

4 个答案:

答案 0 :(得分:0)

在对其进行linq查询之前,检查someDocs是否不是。

同时检查此

GroupBy(x => x.type!= null )

答案 1 :(得分:0)

确定序列是否包含任何元素。

if (devices != null && devices.Any() ) 
{

}

答案 2 :(得分:0)

您是否因为someDocs为空而获得异常? 在您发布的代码中,乍一看,这是唯一可以抛出此异常的地方。

试试这个:

if(someDocs == null){
 someDocs = new List<TypeOfSomeDocsElement>();
}
var devices = someDocs.SelectMany(x => x.Devices).GroupBy(x => x.type);

if (devices != null && devices.Count()>0) // Exception : Object not set to instance of Object 
{
   //my code 
}

答案 3 :(得分:-1)

var devices = someDocs.SelectMany(x => x.Devices)
                      .Where(x.type!=null)
                      .GroupBy(x => x.type);
相关问题