2

Not the most important question in the world but as a soon graduate I figured I would like to have this knowledge going forward. Having said that, how does LINQ find the data I need based on the conditions I provide behind the scenes?

Consider:

String[] straAr = {"Jordan","Jansyn","Corey","Josh","Whitney"};

var sel = from S in straAr
    where S.Contains("syn")
    select S;

This will, of course, result in "Jansyn". Before I was introduced to LINQ, I would have done this:

String[] straAr = {"Jordan","Jansyn","Corey","Josh","Whitney"};

foreach(String s in straAr)
{
    if(s.Contains("syn"))
    {
        Console.WriteLine(s);
    }
}

They both work, though I think LINQs implementation is much more elegant. Can anyone tell me:

  • How does LINQ query a data structure behind the scenes? Foreach?

  • Is one implementation more efficient than the other?

As always, thanks for any input!

svick
  • 236,525
  • 50
  • 385
  • 514
Jason Renaldo
  • 2,802
  • 3
  • 37
  • 48

1 Answers1

3

I think the best way to learn about LINQ internals is by actually looking at the code. Well, you will not be able to look at the original code, but Edulinq is really a great re-implementation of its full functionality for educational purposes.

To answer at least a part of your questions directly:

  • No LINQ typically doesn't use foreach internally. Most of the time, enumerators are used directly because this allows for a finer control of what's going on
  • In general, the second implementation will be more efficient because LINQ offers some additional features (such as laziness) which complicate the generated code a bit. However, this is hardly ever relevant in practice.
David Klempfner
  • 8,700
  • 20
  • 73
  • 153
bigge
  • 1,488
  • 15
  • 27
  • You can look at the original code. I cloned the .NET 5 repo containing Linq, debugged it myself, and wrote an article about how it works behind the scenes: https://levelup.gitconnected.com/linq-behind-the-scenes-efd664d9ebf8?sk=cba7416407ec8b753d9961fe23aac173 – David Klempfner Apr 20 '21 at 10:44