tags:

views:

208

answers:

5

Hi,

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

+5  A: 

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.

Pavel Minaev
A: 

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();
Andrew Koester
You'll also have to find some way to `Add()` the customer if it was newly created.
Pavel Minaev
+1  A: 

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.

Yann Schwartz
A: 

Thanks for the replies. I guess it's easy to get carried away and end up making code less understandable. I did start with

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

But as Pavel noted, still needed a way to add the new customer to the collection.

Thanks Ben

Ben Foster
+1  A: 

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

Bavo