简体   繁体   中英

Lambda expression - add to collection if not present

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

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.

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();

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM