Linq orderby with two custom match sort columns

List<MyObject> objects = (from a in alist
    join b in blist on a.ID equals b.ID
    where a.Number != 4
    orderby b.Rank, a.CustomField
    select a).ToList();

This is my request, and I want to use a custom Comparer for the CustomField property. Is there a way to do this in bipolar order?

I can do it:

List<MyObject> objects = objects.OrderBy(a => a.CustomField, new MyComparer<object>())

but I need it to be sorted by both s.Rank and a.CustomField.

+3
source share
2 answers

Use OrderBy()in conjunction ThenBy()with your custom mappings.

// I'm pretty sure it is not possible to specify
// your custom comparer within a query expression
List<MyObject> objects = (from a in alist
                          join b in blist on a.ID equals b.ID
                          where a.Number != 4
                          select new { a, b })
                         .OrderBy(o => o.b.Rank, new MyRankComparer())
                         .ThenBy(o => o.a.CustomField, new MyComparer<object>())
                         .Select(o => o.a)
                         .ToList();
+8
source

Try the following:

List<MyObject> objects = objects
    .OrderBy(a => a.Rank)
    .ThenBy(a => 
        a.CustomField, new MyComparer<object>()
    ).ToList();

First it is sorted into a field Rank, and then CustomFieldwith your custom mapping.

+5
source

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


All Articles