What is the difference between the two pieces of code below?
This returns the data I expect….
return productTable.FirstOrDefault(p => p.ProductId == productId);
This doesn’t….
return productTable.Where(x => x.ProductId == productId).FirstOrDefault();
I’m mainly just wondering if there’s a logical difference between these two.
Those queries should be essentially identical. The parameterless version of
FirstOrDefault()just grabs the first record available from the query, or default value (i.e., null) if no records are available.Edit 2 As duly pointed out in the comments, I should be using LINQ-to-SQL. Here is a sample with LINQ-to-SQL:
Output (notice the queries are exactly identical):
Edit: Here is sample code to demonstrate they are the same thing: