Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq.Where(x=>x==1) - What Is The Compiler Doing

Tags:

c#

linq

I know Linq is defferedexecution but I want to understand what the compiler does with a statement like this and how it works under the hood

I find Linq fascinating but I worry that I dont understand what is happening under the hood

like image 320
Jack Kada Avatar asked Dec 16 '22 13:12

Jack Kada


2 Answers

Where() is an extension method that could be implemented as something like this:

IEnumerable<T> Where(self IEnumerable<T> sequence, Func<T, bool> predicate) 
{
    foreach(T current in sequence)
        if( predicate(current) )
            yield return current;
}

x => x == 1 is an anonymous procedure that returns true if x == 1 and false otherwise, something like so:

bool predicate(T value)
{
    return value == 1;
}

For the details of how the iterator block in Where() compiles, there's a great series explaining how they are compiled starting here on Eric Lippert's blog.

like image 187
Sean U Avatar answered Jan 10 '23 07:01

Sean U


It's filtering the query to values which are equal to 1. Consider

IEnumerable<int> values = ...;
IEnumerable<int> filteredValues = values.Where(x => x == 1);

Another way to write this would be the following

public static IEnumerable<int> ExampleWhere(IEnumerable<int> values) {
  foreach (var x in values) {
    if (x == 1) {
      yield return 1;
    }
  }
}
like image 44
JaredPar Avatar answered Jan 10 '23 07:01

JaredPar