在这篇 SO 文章中:ascending/descending in LINQ - can one change the order via parameter?提出了如何有条件地按升序或降序排序的解决方案。
这篇文章没有涉及的是,如果我想根据查询中的数据做出决定(实际上,这是最有可能的)怎么办?
我似乎做不到:
source.OrderByWithDirection(o => o.MyColumnToOrderBy, o => o.SortingDirection)
然后我需要重写这些方法吗?怎么办?
-更新-
作为基本原理,这是我希望完成的:
Strike Type Price
98 Ask 101
98 Ask 100
98 Ask 99
98 Bid 95
98 Bid 96
98 Bid 97
如您所见,询价被向下排序,而出价被向上排序,使得差异最大的行彼此相邻。所以我想说的是:
source.OrderBy(o => new { o.Strike, o.Type })
.ThenByWithDirection(o => o.Price, o => o.Type == "Ask" ? __down__ : __up__)
-更新二-
执行此操作的笨拙方法是发出两个单独的查询,如下所示:
source
.Where(o => o.Type == "Ask")
.OrderBy(o => new { o.Strike, o.Type })
.ThenBy(o => o.Price)
source
.Where(o => o.Type == "Bid")
.OrderBy(o => new { o.Strike, o.Type })
.ThenByDescending(o => o.Price)
并连接它们
请您参考如下方法:
我没有你的实体/对象,但你能不能不做这样的事情:
var items = from t in source
select new { a = t, b = t.Type == "Ask" ? -t.Price : t.Price };
var sorted = from x in items
orderby x.a.Type, x.b
select x.a;
也就是说,创建一个包含单个属性的新对象,您可以通过该属性执行排序,然后在您的排序操作中使用它?
