Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Orderby doesn't call Compare() of the provided comparer

Tags:

c#

.net

linq

Can anyone please explain why .net framework doesn't call compare method of my comparer when I use Enumerable.OrderBy. Whereas it does get called when I use List.Sort().

// The code below has been taken from another post on StackOverFlow.com

class Employee
{
    public string Name { get; set; }
    public int Salary { get; set; }
}


class Employee_SortBySalaryByAscendingOrder : IComparer<Employee>
{
    #region IComparer<Employee> Members

    public int Compare(Employee x, Employee y)
    {
        if (x.Salary > y.Salary) return 1;
        else if (x.Salary < y.Salary) return -1;
        else return 0;
    }

    #endregion
}


    private void TestSort(object sender, EventArgs e)
    {

        List<Employee> empList = new List<Employee>() 
                                {       
                                    new Employee { Name = "a", Salary = 14000 },
                                    new Employee { Name = "b", Salary = 13000 } 
                                };
        Employee_SortBySalaryByAscendingOrder eAsc = 
                    new Employee_SortBySalaryByAscendingOrder();
        // Sort Employees by salary by ascending order.   

        // Does not work
        IOrderedEnumerable<Employee> orderedEmployees = empList.OrderBy(x => x, eAsc);

        // Works
        empList.Sort(eAsc);
    }
like image 756
WPFAbsoluteNewBie Avatar asked Dec 20 '22 07:12

WPFAbsoluteNewBie


1 Answers

It doesn't work because you're not actually evaluating the orderedEmployees sequence. You need to force the evaluation using ToList or ToArray.

Linq uses deferred execution so defining your ordering query in:

IOrderedEnumerable<Employee> orderedEmployees = empList.OrderBy(x => x, eAsc);

does not do any work to actually order the input sequence. Only when you try to use the result of the query will the ordering be done.

like image 58
Lee Avatar answered Jan 05 '23 22:01

Lee