Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between extension method and direct query

Tags:

c#

.net

linq

var selectedProducts = from p in products
                       where p.Category == 1
                       select p;

var selectedProducts =  products.Where(p=>p.Category==1) ;

The above 2 statements seems to produce same result.

Then what is the difference(some times internally)?

Which one is efficient more?

like image 256
Kuttan Sujith Avatar asked Feb 25 '23 20:02

Kuttan Sujith


2 Answers

There is no difference. The first (the query expression) is translated to the second by the compiler, and has no impact on run time.

See also:

  • How query expressions work - By Jon Skeet
  • Query transformations are syntactic - By Eric Lippert
like image 139
Kobi Avatar answered Feb 27 '23 17:02

Kobi


There isn't any difference between this two way in this case, but in some cases is better use query and In some cases is better to use extension method or impossible to use query.

you can use query in situation which are complicated with extension methods and unreadable like Join. Also you can use extension method in some cases like Distinct which is not available in query syntax, Also you can use extension method calls for using method chaining to improve your code readability.

You can use mix of extension method and query but is not good (code readability): like

(from p in products
where p.Category == 1
select p).Distinct()
like image 31
Saeed Amiri Avatar answered Feb 27 '23 16:02

Saeed Amiri