0

I am trying to group by my results and the check null but it throwing error on .Any() or .Count() and someDocs is in memory collection

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 
}

How can I check that grouped result is null?

Govind Malviya
  • 13,627
  • 17
  • 68
  • 94

4 Answers4

0

Check if someDocs is not not, before doing a linq query over it.

Also check this

GroupBy(x => x.type!= null )
maxspan
  • 13,326
  • 15
  • 75
  • 104
0

to Determines whether a sequence contains any elements.

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

}
Damith
  • 62,401
  • 13
  • 102
  • 153
0

Are you perhaps getting the exception because someDocs is null? In the code that you posted, at first sight, this is the only place that this exception could be thrown.

Try this:

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 
}
sTodorov
  • 5,435
  • 5
  • 35
  • 55
-1
var devices = someDocs.SelectMany(x => x.Devices)
                      .Where(x.type!=null)
                      .GroupBy(x => x.type);
Deidah
  • 11
  • 4