Sergey Metlov
Sergey Metlov

Reputation: 26341

Custom sorting of the collection

I have collection of objects. I need to sort it by difficult condition, using many properties and calculations. My solution is to define in object special int property, that returns value, that OrderBy shoultd sort by. This solution is not good enough.
For example, collection should be sorted first by State property, then if State = 1, by Value1 property, if State = 2, by Value2 property and so on.
Advice, please, some solution.

Upvotes: 0

Views: 220

Answers (3)

J. Ed
J. Ed

Reputation: 6752

you can use an IComparer class;
just put all the logic you've given above into its compare method.

Upvotes: 0

dtb
dtb

Reputation: 217401

You can order a collection by multiple criteria by using OrderBy for the first criterium and chaining the other criteria after that using ThenBy.

Your first criterium is to simply order by the State property. Your second criterium depends on the State property; assuming that Value1, Value2 and so on have the same type, you can use a switch statement to select the right value:

IEnumerable<MyClass> result = items
    .OrderBy(item => item.State)
    .ThenBy(item =>
    {
        switch (item.State)
        {
            case 1: return item.Value1;
            case 2: return item.Value2;
        }
        throw new Exception();
    });

Upvotes: 2

Muhammad Hasan Khan
Muhammad Hasan Khan

Reputation: 35146

Implement IComparer and using OrderBy of LINQ

Upvotes: 1

Related Questions