views:

60

answers:

2
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 query and I want to use a custom Comparer for the CustomField property. Is there a way to do that in a two-field orderby?

I am able to do this:

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.

+1  A: 

Try this:

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

It first sorts by Rank field and then by CustomField with your custom comparer.

Alex
+1  A: 

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

// 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();
Jeff M
I'm gonna select yours as the right answer because you were first, but I also used Alex's suggestion of using ThenBy instead of the second OrderBy.
morsanu
Ah sorry about that, I _did_ mean `.OrderBy().ThenBy()` but mistyped the example code. Must have looked weird to see be type that in the explanation but not use it in the example. :)
Jeff M