Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GroupBy with Id of possible null object

Tags:

c#

linq

I have a List<Item>

Each Item have a Program, which have an Id.

If an Item is not yet linked to a program, It's program will be null.

I'd like to group all Items by it's Program's Id

That's what I've tried:

var listaAgrupada = client.ListarItens(null, null, null).GroupBy(x => x.Programa.Id).ToList(); 

This works if all Items have a program. But if a program is null, it throws an System.NullReferenceException:

Message = "Object reference not set to an instance of an object."

I believe this is due to the fact that, as Program is null, I can't access it's Id.

I need all Items, even if their program is null (and I'd like them grouped by null program either), so excluding them is not an option.

I've thought in two possible solutions, but I'm not sure how to do any of them:

One would be something like this GroupBy(x => x.Programa == null || x.Programa.Id) (which doesn't work)

The other would be add an empty program object where program is null, but I don't know how to do this

Of course, I'm also open to other solutions

Thanks in advance

like image 867
Ortiga Avatar asked Apr 25 '11 20:04

Ortiga


People also ask

How do I put NULL values in GroupBy?

We can see that the first result value is a NULL represented by an empty string (the empty line before the IT department). This empty space represents all the NULL values returned by the GROUP BY clause, so we can conclude that GROUP BY treats NULLs as valid values.

How do you handle Null in LINQ query?

If a source collection is null or contains an element whose value is null , and your query doesn't handle null values, a NullReferenceException will be thrown when you execute the query. var query1 = from c in categories where c != null join p in products on c.ID equals p?.

Does GroupBy preserve order C#?

Found answer on MSDN: Yes.

How does GroupBy work Linq?

GroupBy allows you to quickly group collections of related data by specific properties on your data. The grouped data is then arranged by sub-collections of items in those groups. Note: LINQ provides variants of each method in this article that work with either IEnumerable or IQueryable .


2 Answers

Assuming you can group all the null Programs together and Id will be non-negative, how about something like this:

GroupBy(x => x.Programa == null ? -1 : x.Programa.Id) 
like image 91
dcp Avatar answered Sep 21 '22 17:09

dcp


With the new C# 6.0 you can also use:

.GroupBy(x => x.Programa?.Id) 

where the ?. is the null-conditional operator. This possibility was not available when the question was asked.

like image 33
Jeppe Stig Nielsen Avatar answered Sep 21 '22 17:09

Jeppe Stig Nielsen