views:

61

answers:

2

If I have the following how to do I cast the result of the lambda expression back to the Customer type from IEnumerable without having to iterate over it.

public class Customer : CustomerModel
    {
        public List<Customer> CustomerList {get;set;}

        public Customer GetCustomerFromListById(long id)
        {
            return CustomerList.Select(c => c).Where(i => i.Id == id);
        }
    }
+2  A: 

Use FirstOrDefault().

   return CustomerList.Select(c => c).Where(i => i.Id == id).FirstOrDefault();
Hans Passant
Even better. Use the overload on FirstOrDefault that takes the `Func<T,bool>` lambda directly as argument
flq
+6  A: 

Use .Single(), also Select is redundant:

return CustomerList.Single(i => i.Id == id);

As mentioned in the comments that way you get an exception if it doesn't contain the needed key, which should be the expected behavior.

Grozz
+1, `Single` is the more appropriate operator for finding by a primary key.
Kirk Woll
May note that single throws an exception... that is often a source of surprise and frustration to new LINQ users.
Rex M
@Rex, your comment is worth mentioning, but I wouldn't use it for querying by primary key. If it's not found, that's a serious error and *should* be an exception.
Kirk Woll
@kirk of course
Rex M