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, ev开发者_如何学JAVAen 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
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.
Mixing both answers, this also can be use:
.GroupBy(x => x?.Programa?.Id ?? -1)
Using "??" defines a default value in case "x" or "x.Program" are null.
精彩评论