拉姆达“如果”陈述?
我有 2 个对象,我想将它们转换为字典。我使用 toDictionary<>()。
一个对象获取密钥的 lambda 表达式是 (i => i.name)。对于另一个,它是(i => i.inner.name)。在第二个中,i.name 不存在。如果 i.name 不存在,则 i.inner.name 始终存在。
是否可以使用 lambda 表达式来组合这两者?基本上读作:
“如果 i.name 存在,则将 id 设置为 i.name,否则将 id 设置为 i.inner.name”。
非常感谢。
更新
当我说“不存在”时,我的意思是对象实际上不具有属性,而不是属性只是空。
I have 2 objects, both of which I want to convert to dictionarys. I use toDictionary<>().
The lambda expression for one object to get the key is (i => i.name). For the other, it's (i => i.inner.name). In the second one, i.name doesn't exist. i.inner.name ALWAYS exists if i.name doesn't.
Is there a lambda expression I can use to combine these two? Basically to read as:
"if i.name exists then set id to i.name, else set id to i.inner.name".
Many thanks.
Update
When I say "don't exist", I mean the objects don't actually have the properties, not that the properties are just null.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果这是两种不同的(参考)类型,那么您可以使用
测试它们是
或为
< /a> 关键字:如果您无法测试特定类型,则可以使用反射来测试
name
属性本身:If these are two distinct (reference) types then you can test them using the
is
oras
keywords:If you can't test for specific types then you can use reflection to test for the
name
property itself:是的,条件运算符(“三元运算符”)可以满足您的要求:
当然,假设您可以通过检查
null
来检测名称的“存在”。编辑:在这种情况下,Kirschstein 的答案当然更好。
Yes, the conditional operator ("ternary operator") does what you want:
Assuming, of course, that you can detect the "existence" of the name by checking for
null
.Edit: In that case, Kirschstein's answer is better, of course.
为什么不给每个对象一个自己的
ToDictionary
方法,因为在这种情况下它们显然有自己的行为。如果您无法添加对象,因为您不拥有它们,您始终可以为它们编写扩展方法。
你有什么理由试图强迫它们进入一个“通用”功能?
Why don't you give each object a
ToDictionary
method of their own, as they obviously have their own behaviours in this case.If you can't add to the objects, because you don't own them, you can always write extension methods for them.
Any reason your trying to force feed them into one "common" function?
类似(未经测试)的东西应该可以解决问题
如果 i.name 不为 null(空字符串),或者
(也未经测试),
something along the lines of
(untested) should do the trick if i.name is not null (an empty string), or
(also untested)
作为内联 if 查询,我将使用三元运算符,因此:
as an inline if query I would use a ternary operator, so: