Linq to SQL - which is better?

db.Albums.FirstOrDefault(x => x.OrderId == orderId)

or

db.Albums.FirstOrDefault(x => x.OrderId.Equals(orderId))
+5
source share
4 answers

Both will be equivalent in terms of performance. I prefer to use more .Equals () for readability, but the beauty of L2S is that you can use any of them, depending on what type of object you have.

(And I assume that your second statement is on orderId and not on the order object)

+7
source

I will try to convince you that:

  • The two methods you proposed give the same performance.
  • There are at least two non-performance reasons you should prefer ==.
  • , , .

, , SQL, . , SQL:

int orderId = 4;
TextWriter textWriter = new StringWriter();
using (var dc = new DataClasses1DataContext())
{
    dc.Log = textWriter;
    Order o1 = dc.Orders.FirstOrDefault(x => x.OrderId == orderId);
    Order o2 = dc.Orders.FirstOrDefault(x => x.OrderId.Equals(orderId));
}
string log = textWriter.ToString();

SQL, , , , :

SELECT TOP (1) [t0].[OrderId], [t0].[CustomerID], [t0].[Date], [t0].[Description]
FROM [dbo].[Order] AS [t0]
WHERE [t0].[OrderId] = @p0

SELECT TOP (1) [t0].[OrderId], [t0].[CustomerID], [t0].[Date], [t0].[Description]
FROM [dbo].[Order] AS [t0]
WHERE [t0].[OrderId] = @p0

== Equals, -, == . #.

-, == , () . , order int, , - , order order int. , :

Order order = new Order { OrderId = 4 };

x.OrderId.Equals(order)  // This compiles, but you get an exception at runtime:
                         // Could not format node 'Value' for execution as SQL.

x.OrderId == order       // Compile error: Operator '==' cannot be applied to
                         // operands of type 'int' and 'Order'

, , == .

, , SingleOrDefault FirstOrDefault, , , . , . , , .

, :

Album album = db.Albums.SingleOrDefault(x => x.OrderId == orderId);
+9

. .

Equals , . == , .

==, .

+1
source

It is almost the same. If you want to check only the value, you should use

==

If you want to check the value, as well as the same instances or not to use

Equally

But in both cases, the resulting time is almost the same.

0
source

All Articles