Scooter
Scooter

Reputation: 21

C# List Order By

I am attempting to implement a custom sort for a Razor Webgrid. Specifically, I want to sort on a column that does not appear in the webgrid itself.

I am going out of my mind trying to figure out why ListOfMatching will not sort. Any ideas would be greatly appreciated.

Thank you

        ResultsDisplayModel foo;        // MVVM class to be bound to the view
                                        // List of Matching is bound to a webgrid

//    public List<ResultsModel> ListOfMatching { get; set; }
//    TotalDebt is in a base class of ResultsModel called Expenses

        if (sort == "DebtBurden")
        {

            if (foo.bSortDirection)
            {
                foo.bSortDirection = false;
                foo.ListOfMatching.OrderByDescending(x => x.TotalDebt);
            }
            else
            {
                foo.bSortDirection = true;
                foo.ListOfMatching.OrderBy(x => x.TotalDebt);
            }
        }

Upvotes: 2

Views: 1933

Answers (2)

Ufuk Hacıoğulları
Ufuk Hacıoğulları

Reputation: 38508

Extension methods in LINQ are side-effect free by default (meaning, they don't modify the original collection in-place). You have to assign the resulting collection to a new variable or overwrite the old one.

foo.ListOfMatchingColleges = foo.ListOfMatchingColleges
                                .OrderBy(x => x.TotalDebt)
                                .ToList();

Upvotes: 6

alexn
alexn

Reputation: 59002

OrderBy and OrderByDescending will not modify the list, but return a new list of sorted element. You have to reassign your properties:

foo.ListOfMatchingColleges = foo.ListOfMatching.OrderByDescending(x => x.TotalDebt);

Upvotes: 4

Related Questions