What is the difference between these 2 XML LINQ Queries? - c#

I have the 2 following LINQ queries and I haven't quite got my head around LINQ so what is the difference between the 2 approaches below?
Is there a circumstance where one approach is better than another?
ChequeDocument.Descendants("ERRORS").Where(x=>(string)x.Attribute("D") == "").Count();
(from x in ChequeDocument.Descendants("ERRORS") where
(string)x.Attribute("D") == ""
select x).Count())

As Darin says, there's no difference. Personally I would prefer the first syntax, as all you've got is a single where clause in the query expresion. Note that the first syntax is more readable as:
var query = ChequeDocument.Descendants("ERRORS")
.Where(x=>(string)x.Attribute("D") == "")
.Count();
Also note that this is demonstrating a special case of query expressions. The second syntax is initially translated into:
var query = ChequeDocument.Descendants("ERRORS")
.Where(x=>(string)x.Attribute("D") == "")
.Select(x => x)
.Count();
but the compiler remove the no-op Select(x => x). It doesn't do this in the case where there are no other clauses - so from x in y select x still becomes y.Select(x => x).

There's no difference at all. The compiler converts the second syntax to the first one (look with Reflector at the compiled assembly) so it's really up to you to decide which syntax suits you best.

For me it the same. Only difference is that 1st is write with lambda expression, second with linq to xml.

Related

Difference between Query Expression and Method Expression in LINQ?

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$.

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

what is the name of this kind of query and difference between using them

What is the name of these two kind of query?
return (from c in _dbRead.Domain
where c.ID == ID
select c).FirstOrDefault();
return _dbRead.Domain.Where(x => x.ID == ID).FirstOrDefault();
I mean let's say i call first one as "linq to sql query" what do i name the second query, ofcourse second one is also "linq to sql query" but what do i name the second query.
And please tell me, what's the difference between using them?
The first one uses the query expression syntax, while the second uses method syntax.
They are effectively the same thing: the compiler transforms the first version into the second (you can read more about this transformation process in part 41 of Jon Skeet's Edulinq series). There is no semantic or performance difference between the two.
x => x.ID == ID in specific are called lambda expressions. Apart from that,there is no special names for such queries.
The first version uses query-comprehension syntax, whereas the second uses extension methods. They are both forms of LINQ.

LINQ Query Syntax to Lambda

Wondering if there is any way to get the lambda expressions that result from a LINQ "query" syntax expression.
Given:
var query = from c in dc.Colors
where c.ID == 213
orderby c.Name, c.Description
select new {c.ID, c.Name, c.Description };
Is there any way to get the generated "lambda" code / expression?
var query = dc.Colors
.Where(c => c.ID == 213)
.OrderBy(c => c.Name)
.ThenBy(c => c.Description)
.Select(c => new {c.ID, c.Name, c.Description, });
I know these are very simple examples and that the C# compiler generates a lambda expression from the query expression when compiling the code. Is there any way to get a copy of that expression?
I am hoping to use this as a training tool for some of my team members that aren't very comfortable with lambda expressions. Also, I have used Linq Pad, but ideally this can be accomplised without a 3rd party tool.
Simply go:
string lambdaSyntax = query.Expression.ToString();
The disadvantage compared to LINQPad is that the result is formatted all one line.
You could try compiling the assembly and then having a look at it using Reflector.
This might be a bit more complicated than you want though, because the compiler will compile things right down to the direct method calls (everything will be static method calls, not extension methods, and the lambdas will get compiled into their own functions which are usually called something like <ClassName>b_88f)
You'll certainly figure out what's going on though :-)
ReSharper has that feature. It will take a LINQ to Lambda and back again at the stroke of a key. Also very (very) useful for other things.

Fluent and Query Expression — Is there any benefit(s) of one over other?

LINQ is one of the greatest improvements to .NET since generics and it saves me tons of time, and lines of code. However, the fluent syntax seems to come much more natural to me than the query expression syntax.
var title = entries.Where(e => e.Approved)
.OrderBy(e => e.Rating).Select(e => e.Title)
.FirstOrDefault();
var query = (from e in entries
where e.Approved
orderby e.Rating
select e.Title).FirstOrDefault();
Is there any difference between the two or is there any particular benefit of one over other?
Neither is better: they serve different needs. Query syntax comes into its own when you want to leverage multiple range variables. This happens in three situations:
When using the let keyword
When you have multiple generators (from clauses)
When doing joins
Here's an example (from the LINQPad samples):
string[] fullNames = { "Anne Williams", "John Fred Smith", "Sue Green" };
var query =
from fullName in fullNames
from name in fullName.Split()
orderby fullName, name
select name + " came from " + fullName;
Now compare this to the same thing in method syntax:
var query = fullNames
.SelectMany (fName => fName.Split().Select (name => new { name, fName } ))
.OrderBy (x => x.fName)
.ThenBy (x => x.name)
.Select (x => x.name + " came from " + x.fName);
Method syntax, on the other hand, exposes the full gamut of query operators and is more concise with simple queries. You can get the best of both worlds by mixing query and method syntax. This is often done in LINQ to SQL queries:
var query =
from c in db.Customers
let totalSpend = c.Purchases.Sum (p => p.Price) // Method syntax here
where totalSpend > 1000
from p in c.Purchases
select new { p.Description, totalSpend, c.Address.State };
I prefer to use the latter (sometimes called "query comprehension syntax") when I can write the whole expression that way.
var titlesQuery = from e in entries
where e.Approved
orderby e.Rating
select e.Titles;
var title = titlesQuery.FirstOrDefault();
As soon as I have to add (parentheses) and .MethodCalls(), I change.
When I use the former, I usually put one clause per line, like this:
var title = entries
.Where (e => e.Approved)
.OrderBy (e => e.Rating)
.Select (e => e.Title)
.FirstOrDefault();
I find that a little easier to read.
Each style has their pros and cons. Query syntax is nicer when it comes to joins and it has the useful let keyword that makes creating temporary variables inside a query easy.
Fluent syntax on the other hand has a lot more methods and operations that aren't exposed through the query syntax. Also since they are just extension methods you can write your own.
I have found that every time I start writing a LINQ statement using the query syntax I end up having to put it in parenthesis and fall back to using fluent LINQ extension methods. Query syntax just doesn't have enough features to use by itself.
In VB.NET i very much prefer query syntax.
I hate to repeat the ugly Function-keyword:
Dim fullNames = { "Anne Williams", "John Fred Smith", "Sue Green" };
Dim query =
fullNames.SelectMany(Function(fName) fName.Split().
Select(Function(Name) New With {Name, fName})).
OrderBy(Function(x) x.fName).
ThenBy(Function(x) x.Name).
Select(Function(x) x.Name & " came from " & x.fName)
This neat query is much more readable and maintainable in my opinion:
query = From fullName In fullNames
From name In fullName.Split()
Order By fullName, name
Select name & " came from " & fullName
VB.NET's query syntax is also more powerful and less verbose than in C#: https://stackoverflow.com/a/6515130/284240
For example this LINQ to DataSet(Objects) query
VB.NET:
Dim first10Rows = From r In dataTable1 Take 10
C#:
var first10Rows = (from r in dataTable1.AsEnumerable()
select r)
.Take(10);
I don't get the query syntax at all. There's just no reason for it in my mind. let can be acheived with .Select and anonymous types. I just think things look much more organized with the "punctuation" in there.
The fluent interface if there's just a where. If I need a select or orderby, I generally use the Query syntax.
Fluent syntax does seem more powerful indeed, it should also work better for organizing code into small reusable methods.
I know this question is tagged with C#, but the Fluent syntax is painfully verbose with VB.NET.
I really like the Fluent syntax and I try to use it where I can, but in certain cases, for example where I use joins, I usually prefer the Query syntax, in those cases I find it easier to read, and I think some people are more familiar to Query (SQL-like) syntax, than lambdas.
While I do understand and like the fluent format , I've stuck to Query for the time being for readability reasons. People just being introduced to LINQ will find Query much more comfortable to read.
I prefer the query syntax as I came from traditional web programming using SQL. It is much easier for me to wrap my head around. However, it think I will start to utilize the .Where(lambda) as it is definitely much shorter.
I've been using Linq for about 6 months now. When I first started using it I preferred the query syntax as it's very similar to T-SQL.
But, I'm gradually coming round to the former now, as it's easy to write reusable chunks of code as extension methods and just chain them together. Although I do find putting each clause on its own line helps a lot with readability.
I have just set up our company's standards and we enforce the use of the Extension methods. I think it's a good idea to choose one over the other and don't mix them up in code. Extension methods read more like the other code.
The comprehension syntax does not have all operators and using parentheses around the query and add extension methods after all just begs me for using extension methods from the start.
But for the most part it is just personal preference with a few exceptions.
From Microsoft's docs:
As a rule when you write LINQ queries, we recommend that you use query syntax whenever possible and method syntax whenever necessary. There is no semantic or performance difference between the two different forms. Query expressions are often more readable than equivalent expressions written in method syntax.
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/#query-expression-overview
They also say:
To get started using LINQ, you do not have to use lambdas extensively. However, certain queries can only be expressed in method syntax and some of those require lambda expressions.
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/query-syntax-and-method-syntax-in-linq

Categories

Resources