Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is the better method to use LINQ?

Tags:

c#

linq

I have these two lines, that do exactly the same thing. But are written differently. Which is the better practice, and why?

firstRecordDate = (DateTime)(from g in context.Datas
                                   select g.Time).Min();

firstRecordDate = (DateTime)context.Datas.Min(x => x.Time);
like image 621
Since_2008 Avatar asked Aug 19 '11 15:08

Since_2008


2 Answers

there is no semantic difference between method syntax and query syntax. In addition, some queries, such as those that retrieve the number of elements that match a specified condition, or that retrieve the element that has the maximum value in a source sequence, can only be expressed as method calls.

http://msdn.microsoft.com/en-us/library/bb397947.aspx

Also look here: .NET LINQ query syntax vs method chain

It comes down to what you are comfortable with and what you find is more readable.

like image 108
manojlds Avatar answered Oct 07 '22 02:10

manojlds


The second one use lambda expressions. I like it as it is compact and easier to read (although some will find the former easier to read).

Also, the first is better suited if you have a SQL background.

like image 36
Mrchief Avatar answered Oct 07 '22 01:10

Mrchief