Lambda 表达式 - 如果不存在则添加到集合中

发布于 2024-08-13 12:07:46 字数 463 浏览 2 评论 0原文

我刚刚开始学习 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

滥情稳全场 2024-08-20 12:07:46

正如所写的那样,它似乎并没有比保持清晰和可读所需的时间更长。当然有一些黑客方法可以滥用 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.

哽咽笑 2024-08-20 12:07:46

帕维尔是对的。顺便说一句,如果您在循环中执行此操作,则除了集合本身之外,您还需要使用 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.

智商已欠费 2024-08-20 12:07:46

这可能是你能想到的最“简单”的东西,但正如帕维尔所说,将其写在一行上有点老套。无论如何,如果你好奇的话,它就在这里。

Customer customer = Customers.FirstOrDefault(c => c.ID == 3).DefaultIfEmpty(new Customer() { FirstName = "Ben", LastName = "Foster", ID = 3 });
customer.CreateProfile();

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.

Customer customer = Customers.FirstOrDefault(c => c.ID == 3).DefaultIfEmpty(new Customer() { FirstName = "Ben", LastName = "Foster", ID = 3 });
customer.CreateProfile();
萌酱 2024-08-20 12:07:46

您可以使用 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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文