Difference between Query Expression and Method Expression in LINQ? - c#

I don't know whether the term of above title is appropriate.
Just like a and b:
var list = Enumerable.Range(0, 100);
var a = from l in list
where l % 2 == 0
select l;
var b = list.Where(l => l % 2 == 0);
When should I use each of them? And any difference?

None, Query expression compiles into Method expression.
Query Syntax and Method Syntax in LINQ (C#)
Because queries return an IEnumerable, you compose them in method
syntax by chaining the method calls together. This is what the
compiler does behind the scenes when you write queries by using query syntax
Also see: 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. For more information, see
C# Language Specification and Standard Query Operators Overview.
Apart from that one place where I have found something that can't be done in Query expression is to get the index along with the item. For example you can do following in method syntax:
var result = list.Select((r,i) => new { value = r, index = i});
In query expression an external variable has to be defined to achieve this purpose. Here is a similar discussion with answer from Jon Skeet

No
There is no difference between them.
From Query Syntax and Method Syntax in LINQ
Because queries return an IEnumerable, you compose them in method
syntax by chaining the method calls together. This is what the
compiler does behind the scenes when you write queries by using query
syntax. And because a query variable does not store the results of the
query, you can modify it or use it as the basis for a new query at any
time, even after it has been executed.
Also from LINQ Query Expressions
At compile time, query expressions are converted to Standard Query
Operator method calls.

Query expression is transformed into standard method calls by compiler.
var a = from l in list
where l % 2 == 0
select l;
var b = list.Where(l => l % 2 == 0);
These two are exactly the same in compiled code.
However, not all methods have a keyword associated in query expression syntax.

There's no difference, it's a matter of personal preference. You can even mix the two styles if you want to.
The Linq keywords are translated into the method call syntax by the C# compiler.

The difference, in fact, is no.
In fact, it is one and the same thing, except that the expression for the $a$ the compiler converts to an expression equivalent to expression for $b$.

Related

What is the difference between Linq and EF syntax? [duplicate]

This question already has answers here:
Is it Linq or Lambda?
(2 answers)
Closed 5 years ago.
What is difference of
Linq: var data=from a in context.object select a;
EF: var data=context.object().Tolist();
They are both LINQ.
The first is query (expression) syntax
IEnumerable<int> numQuery1 =
from num in numbers
where num % 2 == 0
orderby num
select num;
And the other is method syntax
IEnumerable<int> numQuery2 = numbers
.Where(num => num % 2 == 0)
.OrderBy(n => n);
Source: MSDN: Query Syntax and Method Syntax in LINQ (C#)
In your case the difference is that in first case data will be of lazy IEnumerable type and and will be executed on enumerating it.
Second example will enumerate colletion to a list and collection will be in memory after execution of ToList method.
But I assume you are interested in difference between LINQ operators like from, where, select and method Where, Select, etc. There is not difference as operators are compiled to methods.
Difference between both syntax is:
Your 1st query is LINQ to Sql and 2nd one is Entity SQL.
Entity SQL is processed by the Entity Framework Object Services directly
Entity SQL returns ObjectQuery instead of IQueryable
You mean to know the kinds of difference in query syntax while Entity Framework.
Basics of LINQ & Lamda Expressions
LINQ
Linq is the Microsoft's first attempt to integrate queries into language. We know, it is really easy to find data from sql objects simply writing a query while its somewhat hectic when we want to do the same thing in a DataTable or Lists. Generally we will have to loop through every elements to find the exact match, if there is some aggregation we need to aggregate the values etc. Linq provides an easy way to write queries that can run with the in memory objects.
Lamda
A lambda expression is an anonymous function that you can use to create delegates or expression tree types. By using lambda expressions, you can write local functions that can be passed as arguments or returned as the value of function calls. Lambda expressions are particularly helpful for writing LINQ query expressions.
Hope it Helps.

Differences in LINQ vs Method expression

Why the Linq expression IL results in omission of the Select projection whereas the corresponding method expression keeps the Select projection ?
I suppose these two pieces of code does the same.
var a = from c in companies
where c.Length >10
select c;
//
var b = companies.Where(c => c.Length > 10).Select(c => c);
//IL - LINQ
IEnumerable<string> a = this.companies.
Where<string>(CS$<>9__CachedAnonymousMethodDelegate1);
//IL
IEnumerable<string> b = this.companies.Where<string>
(CS$<>9__CachedAnonymousMethodDelegate4).Select<string, string>
(CS$<>9__CachedAnonymousMethodDelegate5);
Then why the difference in IL?
EDITED :
then why
var a = from c in companies
select c;
result in SELECT projection even inside IL. it can also be omitted right ?
The C# compiler is clever and remove useless statement from Linq. Select c is useless so the compiler remove it. When you write Select(c=>c) the compiler can't say that's the instruction is useless because it' a function call and so it doesn't remove it.
If you remove it yourself IL become the same.
EDIT :
Linq is a "descriptive" language : you say what you want and the compiler transforms it well. You don't have any control on that transformation. The compiler try to optimize function call and don't use Select because you don't do projection so it's useless.
When you write Select(c => c) you call a function explicitely so the compiler won't remove it.
var a = from c in companies select c;
var a = c.Select(elt=>elt);
Select is usefull in this example. If you remove it a has the type of c; otherwise a is an IEnumerable
#mexianto is of course correct that this is a compiler optimization.
Note that this is explicitly called out in the language specification under "Degenerate Query expressions." Also note that the compiler is smart enough to not perform the optimization when doing so would return the original source object (the user might want to use a degenerate query to make it difficult for the client to mutate the source object, assuming that it is mutable).
7.16.2.3 Degenerate query expressions
A query expression of the form
from x in e select x
is translated into
( e ) . Select ( x => x )
[...] A degenerate query expression is one that
trivially selects the elements of the source. A later phase of the
translation removes degenerate queries introduced by other translation
steps by replacing them with their source. It is important however to
ensure that the result of a query expression is never the source
object itself, as that would reveal the type and identity of the
source to the client of the query. Therefore this step protects
degenerate queries written directly in source code by explicitly
calling Select on the source. It is then up to the implementers of
Select and other query operators to ensure that these methods never
return the source object itself.
In your second example, the call to Select is not redundant. If you would omit the Select call, the query would just return the original collection, whereas Select returns an IEnumerable.
In your first example, Where already returns an IEnumerable and the select clause doesn't do any work, so it is omitted.
Because in the query version there is no actual select projecting 'c' into something else, it is just passing on 'c' as-is. Which results in only a call to 'Where'.
In the second variation, you explicitly call 'Select' and thus do a projection. Yes, you are only returning the same objects, but the compiler will not see this.

Difference between extension method and direct query

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?
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
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()

How to pass parameters to LINQ to XML query by using lambda expression?

I am new to LINQ to XML in .net(C#, asp.net). I want to know more about Lambda expressions. I am using Lambada expression with the following query.
count = FieldRoot.Element("USER").Element("MM")
.Descendants("MMMS")
.Where(a => a.Attribute("ID").Value == MID)
.SelectMany(b => b.Descendants("ABC")).Count();
Can you please tell me how the Lambda expression work specially in case of parameters (in the above case a & b) ? What is the basic concept of parameters in Lambda expression ? Can we use the names of the variables defined outside of the query instead of a & b ? which elements a & b represent in the above case represent ? Can we pass parameters from outside in the query ? If we can pass parameters from outside query then how it will be done? If you give me any other example instead of the above query to understand the concept of parameter in Lambda expression then it will also help me a lot.
The basic concept is that you're calling Where on a sequence of XElement values - so the lambda expression is executed several times, with a value for a as the "current" XElement. The lambda expression then says whether or not that XElement should be included in the results.
For the SelectMany call, this is effectively flattening a sequence of sequences - from one XElement, you're yielding a sequence of all the ABC descendant elements.
This is really just LINQ to Objects - it's just that LINQ to XML fits in very neatly with LINQ to Objects.

Reusing Expression in Linq select clause (query format)

I have an Expression that converts one type of object to another type. The expression is as follows:
public Expression<Func<SQLRepository.ActionType, Model.ActionType>> DBActionTypeToActionType =
(SQLRepository.ActionType at) => new Model.ActionType()
{
ID = at.OID,
DisplayName = at.DisplayName
};
I can use the Expression like this:
var linq = (from at in dc.SQLRepositoryDC.ActionTypes select at).Select(DBActionTypeToActionType);
But I'd like to use it like this:
var linq = (from at in dc.SQLRepositoryDC.ActionTypes select DBActionTypeToActionType.Compile().Invoke(at));
I've been looking for a couple days now and I can only find references to doing this in the Where clause. It seems that if I'm able to use the function calls to do this, it should be possible using the query syntax.
The reason it is important to do use the query syntax is that some of the objects that are being selected are composed of many sub-objects and trying to chain them all of the conversions together with the function notation will be much harder to write and maintain.
It seems that if I'm able to use the function calls to do this, it should be possible using the query syntax.
That's not true. Query notation always goes via a lambda expression. For example
from x in y select z
ends up as
y.Select(x => z)
That means if you've already got an expression tree that you want to pass directly as the argument to Select, you can't use query expressions because there's this extra level of indirection.
Now the options available depend on where you need to apply the predefined expression. You can always use it in the source, and then continue with the query:
var query = from foo in dc.ActionTypes.Select(DBActionTypeToActionType)
where foo.Stuff
select foo.Other;
Or using it at the end is easy:
var query = (from bar in dc.ActionTypes
where bar.Stuff
select bar).Select(DBActionTypeToActionType);
Does that help at all?

Categories

Resources