Use one variable across multiple LINQ query chains

Is it fair to use a single lambda expression variable in multiple chain calls? For instance:

MyList.Where(i => i.ID > 20).OrderBy(i => i.Name);

So, iused in Where()does not depend on iused in OrderBy(), or can it have some hidden side effects on each other, so I have to use different variables for each variable? Also, is your answer saved for VB.NET?

I ask this because I read in a slightly different context that I should not use the foreach variable in LINQ queries directly and instead create a local copy of the variable inside the loop. Is there a similar effect hidden in the above code?

+4
source share
4 answers

Lambda expressions are basically a shorter way to write anonymous methods. Therefore, iin your examples, lambda is the same as a parameter in an anonymous method. In other words, they are independent of each other, just as the parameters of different methods are independent of each other.

For ease of reading, it may be appropriate to change ito personor something similar. For instance.MyList.Where(person => person.ID > 20).OrderBy(person => person.Name);

Relative foreach: read about closing in this context on Eric Lippert's blog: http://blogs.msdn.com/b/ericlippert/archive/2009/11/12/closing-over-the-loop-variable-considered-harmful.aspx

Excerpts:

() = > v " v", " v , ". , . , , , v, 120, .

+3

. , , , , labda. , i Where(i => i.ID > 20) i OrderBy(i => i.Name). i MyList, i , Where, MyList, ID>20.

+6

, :

MyList.Where(i => i.ID > 20).OrderBy(i => i.Name);

, i, -. :

int i = 0;
MyList.Where(i => i.ID > 20).OrderBy(i => i.Name);

i lambdas i, .

foreach . :

foreach (var foo in fooList) 
{
    var filteredList = MyList.Where(i => i.ID > foo.Id).OrderBy(i => i.Name);
}

, LINQ foo, , foo. , foo, . , , , , :

var bar = filteredList.ToList();

foo lambda Where foo , , ​​. , foo fooList. , ( ), .

foreach (var foo in fooList) 
{
    var copy = foo;
    var filteredList = MyList.Where(i => i.ID > copy.Id).OrderBy(i => i.Name);
}
+4

See: Variable area in lambda expression - MSDN

The variables entered in the lambda expression are not visible in the external method.

So, in your case, your proposal Where, you have announced i, which is displayed only inside the proposal Whereand, therefore, regardless of the announcement declared in OrderBy.

+2
source

Source: https://habr.com/ru/post/1536977/


All Articles