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
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.
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?.
Found answer on MSDN: Yes.
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 .
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With