Linq orderby two-column sort with custom comparer
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 =&开发者_如何学JAVAgt; a.CustomField, new MyComparer<object>())
but I need it to be sorted by both s.Rank and a.CustomField.
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();
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.
精彩评论