Reputation: 18600
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.
Upvotes: 3
Views: 812
Reputation: 56769
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:
using (ProductsDataContext context = new ProductsDataContext())
{
context.Log = Console.Out;
var p1 = context.Products.FirstOrDefault(p => p.ProductId == 1);
var p2 = context.Products.Where(p => p.ProductId == 1).FirstOrDefault();
}
Output (notice the queries are exactly identical):
SELECT TOP (1) [t0].[ProductId], [t0].[Name] FROM [dbo].[Products] AS [t0] WHERE [t0].[ProductId] = @p0 -- @p0: Input Int (Size = -1; Prec = 0; Scale = 0) [1] -- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 4.0.30319.1
SELECT TOP (1) [t0].[ProductId], [t0].[Name] FROM [dbo].[Products] AS [t0] WHERE [t0].[ProductId] = @p0 -- @p0: Input Int (Size = -1; Prec = 0; Scale = 0) [1] -- Context: SqlProvider(Sql2008) Model: AttributedMetaModel Build: 4.0.30319.1
Edit: Here is sample code to demonstrate they are the same thing:
class Product
{
public int ProductId { get; set; }
public string Name { get; set; }
}
class Program
{
static void Main(string[] args)
{
List<Product> productTable = new List<Product> {
new Product { ProductId = 123, Name = "Cheese" },
new Product { ProductId = 456, Name = "Milk" },
};
var r1 = productTable.FirstOrDefault(p => p.ProductId == 123);
var r2 = productTable.Where(p => p.ProductId == 123).FirstOrDefault();
// these print out the same thing
Console.WriteLine(r1.Name);
Console.WriteLine(r2.Name);
Console.ReadLine();
}
}
Upvotes: 4