WPFAbsoluteNewBie
WPFAbsoluteNewBie

Reputation: 1375

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

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

Upvotes: 4

Views: 1106

Answers (1)

Lee
Lee

Reputation: 144136

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.

Upvotes: 11

Related Questions