tags:

views:

166

answers:

1

What is the difference if any between these two Lambda Expressions ? And the second one seems more compact should I always go for that ?

DataContext.Employee.Where(c=>c.id==check_id && c.username==user_name).Select(c=>c.Name).FirstOrDefault();

and

DataContext.Employee.FirstOrDefault(c=>c.id==check_id && c.username==user_name).Name;
+14  A: 

The second version can throw a NullReferenceException if a matching element is not found and the default value for the type is null.

The first version does not have this problem.

Mark Byers
To add to this, two statements are whole lot of different. First one is doing filtering first and then picking up the first. Second one is picking the first record and then trying to match it up against filtering criteria. Intention is whole lot different and second one seems to give wrong business results (technically it will work).
Pradeep
@Pradeep: You mean that `FirstOrDefault` with condition return first element IF it matches the condition? That's not true. `FirstOrDefault` with condition return first element THAT matches the condition, it can be second one or any other, just the first matching. So the businness result is OK, there is only `NullReferenceException` problem mentioned.
A.