Andre Andre - 24 days ago 8
C# Question

GroupBy with Id of possible null object

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

dcp dcp
Answer

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)
Comments