Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a method chain be called LINQ?

Tags:

c#

linq

Is it correct to call this code snippet LINQ (Language Integrated Query)?

var lstMyStrings = new List<string>();
lstMyStrings.Where(aX => string.IsNullOrEmpty(aX))
            .Skip(3)
            .ToList();

I am confused because System.Linq is mandatory for this code.
However, when I see questions and answer's like this: .NET LINQ query syntax vs method chain , then they're talking explicit about a method chain and not LINQ.

like image 275
Userino Avatar asked Sep 06 '17 08:09

Userino


1 Answers

LINQ can be written in two different ways.
One is by writing a query using LINQ declarative query syntax:

var query = from x in source
            where condition
            select x.Property

And the other is by using LINQ's extension methods:

var query = source.Where(condition).Select(x => x.Property);

Both queries are identical and will produce the same result (well, compiler error in this over-simplified example but it's the thought that counts :-))

The c# compiler translates the query into method calls.
This means that everything you write as a query can be also written using method chains. Please note, however, that the opposite is false - Some queries can only be written using Linq's extension methods.

For further reading, here's what Microsoft have to say about it.

Note the second paragraph starts with this:

Query syntax and method syntax are semantically identical, but many people find query syntax simpler and easier to read.

btw, if it was'nt already clear, the reason that System.Linq is mandatory for the method chaining syntax also is because the linq extension methods belongs to this namespace.

like image 61
Zohar Peled Avatar answered Sep 18 '22 14:09

Zohar Peled