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 co开发者_JAVA技巧llection. 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.
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.
Customer customer = Customers.FirstOrDefault(c => c.ID == 3).DefaultIfEmpty(new Customer() { FirstName = "Ben", LastName = "Foster", ID = 3 });
customer.CreateProfile();
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
精彩评论