Use LINQ for custom 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 the elements in the collection using an arbitrary sort rule without implementing IComparable. I ran into a problem because the business requires that on some screens the elements in the collection are sorted one way and on other screens in some other way. For example, a rule may indicate that items should be sorted so that “b” is first indicated, then “a”, then “c” and within each group “first 3”, then “1”, then “2”.

+1
source share
1 answer

Of course. You can use OrderBywith a predicate that returns a more or less arbitrary arbitrary sort order. 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?
});
+6
source

Source: https://habr.com/ru/post/1719450/


All Articles