C # LINQ Results Mismatch

When I do this:

currentPage = metadataResponse.ApplicationType.Pages.Find( page => page.SortOrder == ++currentPage.SortOrder); 

currentPage is null.

But the same logic when I assign the increment value to an integer variable and then try to get currentPage

 int sortOrder = ++currentPage.SortOrder; currentPage = metadataResponse.ApplicationType.Pages.Find( page => page.SortOrder == sortOrder); 

currentPage populated.

Does anyone have a good answer why it works and the other doesn't?

+5
source share
1 answer

Note. I assume the Find method applies to a set of values.

In the first code example, you increase currentPage for each element of your collection (this is because lambda expressions introduce closures on variables captured from the outer scope - see the code block below for more information on this). In the second code example, currentPage incremented only once. See how the following program behaves:

 class Program { static void Main(string[] args) { Func1(); Console.WriteLine("\n"); Func2(); Console.ReadKey(); } private static void Func1() { int i = 0; var list = new List<int> { 1, 2, 3 }; list.ForEach(x => Console.WriteLine(++i)); } private static void Func2() { int i = 0; int j = ++i; var list = new List<int> { 1, 2, 3 }; list.ForEach(x => Console.WriteLine(j)); } } 

There is more information about closures in lambda expressions. Have some fun !; -)

+6
source

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


All Articles