Linq query or Lambda expression?

2020-01-27 04:43发布

I'm using Entity Framework in my ASP.NET, C#, Web Application. If I need to select a record from DataBase (in Data Access Layer), which method should I use? Linq query or a Lambda Expression?

Eg:-

//Linq        
var result = from a in db.myTable.Take(1) where a.Id == varId  select a;
return result.First();

//Lambda
return db.myTable.FirstOrDefault(a => a.Id == varId);

Is there any preferred way in this scenario or any advantage over the other?

标签: c# linq lambda
5条回答
再贱就再见
2楼-- · 2020-01-27 05:19

I guess the result is the same. Lambda is just a bit more comfortable. If you need a result of just one table, the lambda expression is very fast and readable.

查看更多
对你真心纯属浪费
3楼-- · 2020-01-27 05:26

Query Expression compiles into Method Expression (Lambda expression), so there shouldn't be any difference, In your code though you are accessing First and FirstOrDefault which would behave differently.

See: Query Syntax and Method Syntax in LINQ (C#)

and LINQ Query Expressions (C# Programming Guide)

At compile time, query expressions are converted to Standard Query Operator method calls according to the rules set forth in the C# specification. Any query that can be expressed by using query syntax can also be expressed by using method syntax. However, in most cases query syntax is more readable and concise.

查看更多
男人必须洒脱
4楼-- · 2020-01-27 05:34

Both of your tries use Linq.

The first takes one record and checks if the id matches.

The second takes the first record where the id matches.

That's a difference.

查看更多
劳资没心,怎么记你
5楼-- · 2020-01-27 05:36

Linq query syntax is just a syntax sugar for expression methods. Any Linq query compiled into expression methods. Btw your first query:

var query = from a in db.myTable.Take(1) 
            where a.Id == varId  
            select a;
return query.First();

Is equivalent to

return db.myTable.Take(1).Where(a => a.Id == varId).First();
查看更多
Summer. ? 凉城
6楼-- · 2020-01-27 05:36

Every query expression can be expressed as C#-code using calls to query operators as extension methods. But the opposite is not true; only a small subset of the standard query operators can be used as keywords in query expressions. In other words query expressions have some limitations that the method-call mechanism does not have:

  1. Some query operators have simply no C# query expression equivalent, e.g. ToArray().
  2. We can't use all kinds of overloads in C#'s query expressions. E.g. there is an overload of Select() that awaits the index of the currently iterated object; you cannot call this overload within a query expression.
  3. We can't use statement lambdas in query expressions. - This is the cause why object and collection initializers have been introduced into the C# language.
查看更多
登录 后发表回答