Lambda 表达式 - 如果不存在则添加到集合中
我刚刚开始学习 lambda 表达式。
是否可以进一步简化以下代码:
Customer customer = Customers.FirstOrDefault(c => c.ID == 3);
if (customer == null)
{
customer = new Customer() { FirstName = "Ben", LastName = "Foster", ID = 3 };
Customers.Add(customer);
}
// do something with customer
customer.CreateProfile();
本质上我想检查集合中是否存在对象。如果没有,我想创建它,将其添加到集合中并稍后使用它。
谢谢 本
I have just started learning lambda expressions.
Is it possible to simplify the following code down further:
Customer customer = Customers.FirstOrDefault(c => c.ID == 3);
if (customer == null)
{
customer = new Customer() { FirstName = "Ben", LastName = "Foster", ID = 3 };
Customers.Add(customer);
}
// do something with customer
customer.CreateProfile();
Essentially I want to check if an object exists in a collection. If it doesn't I want to create it, add it to the collection and use it later on.
Thanks
Ben
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
正如所写的那样,它似乎并没有比保持清晰和可读所需的时间更长。当然有一些黑客方法可以滥用 lambda 和运算符
??
进一步将其全部写在一行上,但最终它们只会混淆代码。As written, it seems to be not any longer than needed for it to remain clear and readable. There are certainly hackish ways to abuse lambdas and operator
??
further here to write it all on a single line, but ultimately they only serve to obfuscate code.帕维尔是对的。顺便说一句,如果您在循环中执行此操作,则除了集合本身之外,您还需要使用 HashSet 或某种以 Id 作为搜索键的字典,以免出现 O (n²) 复杂性。
Pavel is right. As an aside, if you're doing this in a loop, you'd want to use a HashSet or some kind of dictionary with the Id as keys in it for your search, beside your collection itself, so as not to have an O(n²) complexity.
这可能是你能想到的最“简单”的东西,但正如帕维尔所说,将其写在一行上有点老套。无论如何,如果你好奇的话,它就在这里。
This is probably as 'simple' as you can get it, but like Pavel said, it's a bit hackish to write it on one line. Here it is anyway, just if you were curious.
您可以使用 Set 实现而不是普通集合。
查看 Iesi.Collections,网址为 http://www.surcombe。 com/nhibernate-1.2/api/html/N_Iesi_Collections.htm
You could use a Set implementation instead of a normal collecion.
Take a look at Iesi.Collections at http://www.surcombe.com/nhibernate-1.2/api/html/N_Iesi_Collections.htm