I have a List<Item>
我有一个List
Each Item have a Program, which have an Id.
每个项目都有一个程序,它有一个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
我想按照程序的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:
如果所有项目都有程序,则此方法有效。但是如果程序为null,则抛出System.NullReferenceException:
Message = "Object reference not set to an instance of an object."
Message =“对象引用未设置为对象的实例。”
I believe this is due to the fact that, as Program is null, I can't access it's Id.
我相信这是因为,由于程序为空,我无法访问它的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)
一个就像这个GroupBy(x => x.Programa == null || x.Programa.Id)(这不起作用)
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
提前致谢
3 个解决方案
#1
27
Assuming you can group all the null
Programs together and Id
will be non-negative, how about something like this:
假设您可以将所有空程序组合在一起并且Id将是非负数,那么如下所示:
GroupBy(x => x.Programa == null ? -1 : x.Programa.Id)
#2
11
With the new C# 6.0 you can also use:
使用新的C#6.0,您还可以使用:
.GroupBy(x => x.Programa?.Id)
where the ?.
is the null-conditional operator. This possibility was not available when the question was asked.
在哪里?是空条件运算符。当问到这个问题时,这种可能性是不可行的。
#3
1
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.
使用“??”在“x”或“x.Program”为空的情况下定义默认值。
#1
27
Assuming you can group all the null
Programs together and Id
will be non-negative, how about something like this:
假设您可以将所有空程序组合在一起并且Id将是非负数,那么如下所示:
GroupBy(x => x.Programa == null ? -1 : x.Programa.Id)
#2
11
With the new C# 6.0 you can also use:
使用新的C#6.0,您还可以使用:
.GroupBy(x => x.Programa?.Id)
where the ?.
is the null-conditional operator. This possibility was not available when the question was asked.
在哪里?是空条件运算符。当问到这个问题时,这种可能性是不可行的。
#3
1
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.
使用“??”在“x”或“x.Program”为空的情况下定义默认值。