epitka
epitka

Reputation: 17627

Use LINQ for arbitrary sorting

Let's say we have an entity that has attributes att1 and att2, where att1 can have values a,b,c and att2 can have values 1,2,3. Is it possible to use LINQ so that we can sort items in the collection by applying arbitrary sorting rule without implementing IComparable. I am facing an issue were business requires that on some screens items in the collection be sorted one way and in other screens some other way. For example rule can state that items need to be sorted so that "b" is listed first, then "a", then "c" and within each group, "3" is first, then "1" then "2".

Upvotes: 2

Views: 681

Answers (1)

mqp
mqp

Reputation: 71937

Sure. You can use OrderBy with a predicate that returns more or less whatever kind of arbitrary "sort order" you please. For example:

objectsWithAttributes.OrderBy(x =>
{
    // implement your "rules" here -- anything goes as long as you return
    // something that implements IComparable in the end.  this code will sort
    // the enumerable in the order 'a', 'c', 'b'

    if (x.Attribute== 'a')
        return 0;
    else if (x.Attribute== 'c')
        return 1;
    else if (x.Attribute== 'b')
        return 2;
}).ThenBy(x =>
{
    // implement another rule here?
});

Upvotes: 7

Related Questions