When I do this:
currentPage = metadataResponse.ApplicationType.Pages.Find(
page => page.SortOrder == ++currentPage.SortOrder);
The value of currentPage
is null.
But the same logic, when I assign the increment value to an integer variable, and then try to get the currentPage
int sortOrder = ++currentPage.SortOrder;
currentPage = metadataResponse.ApplicationType.Pages.Find(
page => page.SortOrder == sortOrder);
currentPage
gets populated.
Does anyone have a good answer as to why one works and the other doesn't?
Definition of discrepancy 1 : the quality or state of disagreeing or being at variance. 2 : an instance of disagreeing or being at variance.
Discrepancy definition Discrepancy is defined as a difference or inconsistency. An example of discrepancy is a bank statement that has a different balance than your own records of the account. noun. 3. An inconsistency between facts or sentiments.
If there is a discrepancy between two things that ought to be the same, there is a noticeable difference between them. If there is a discrepancy between two things that ought to be the same, there is a noticeable difference between them.
Note: I assume Find
method is applied to a collection of values.
In the first code example, you are incrementing currentPage
for each element in your collection (this is happening because lambda expressions introduce closures over variables captured from outer scope - see below code block for more info about that). In the second code example, currentPage
is incremented only once. Take a look 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));
}
}
Here is some more info about closures in lambda expressions. Have fun! ;-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With