具有可能为空对象的 ID 的 GroupBy
我有一个 List
每个项目都有一个程序,其中有一个 ID。
如果项目尚未链接到程序,则其程序将为空。
我想按程序的 ID 对所有项目进行分组
这就是我尝试过的:
var listaAgrupada = client.ListarItens(null, null, null).GroupBy(x => x.Programa.Id).ToList();
如果所有项目都有程序,则此方法有效。但如果程序为 null,则会抛出 System.NullReferenceException:
Message =“对象引用未设置为 对象的实例。”
我相信这是因为,由于程序为空,我无法访问它的 Id。
我需要所有项目,即使它们的程序为空(并且我希望它们按null 程序),所以排除它们不是一个选择,
我想到了两种可能的解决方案,但我不确定如何执行其中任何一个:
一个是这样的 GroupBy(x =>; x.Programa == null || x.Programa.Id)
(这不起作用)
另一个是添加一个空程序对象,其中程序为空,但我不知道如何做到这一点
当然,我也愿意其他解决方案
提前致谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
假设您可以将所有
null
程序分组在一起,并且Id
将为非负数,那么像这样的事情怎么样:Assuming you can group all the
null
Programs together andId
will be non-negative, how about something like this:在新的 C# 6.0 中,您还可以使用:
其中
?.
是 null 条件运算符。当提出问题时,这种可能性不存在。With the new C# 6.0 you can also use:
where the
?.
is the null-conditional operator. This possibility was not available when the question was asked.混合两个答案,也可以使用:
使用“??”定义“x”或“x.Program”为空时的默认值。
Mixing both answers, this also can be use:
Using "??" defines a default value in case "x" or "x.Program" are null.