Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Discrepancy in C# LINQ results

Tags:

c#

.net

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?

like image 215
Arjun Balaji Avatar asked Feb 05 '16 23:02

Arjun Balaji


People also ask

What is the mean by discrepancy?

Definition of discrepancy 1 : the quality or state of disagreeing or being at variance. 2 : an instance of disagreeing or being at variance.

What is discrepancy example?

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.

Is discrepancy same as difference?

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.


1 Answers

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! ;-)

like image 148
Kapol Avatar answered Oct 06 '22 01:10

Kapol