问题描述
在这篇 SO 文章中:ascending/在 LINQ 中降序 - 可以通过参数更改顺序吗? 提出了一种解决方案,说明如何有条件地按升序或降序排序.
本文没有涵盖的是,如果我想根据查询中的数据(实际上,最有可能的是什么)做出决定,该怎么办?
我似乎做不到:
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;
也就是说,创建一个包含单个属性的新对象可以执行排序,然后在排序操作中使用它?
问题描述
In this SO article: ascending/descending in LINQ - can one change the order via parameter? a solution was presented for how to conditionally order in ascending or descending order.
what the article doesn't cover is, what if I want to make the decision based on the data in the query (which is, actually, what is most likely)?
I cannot seem to do:
source.OrderByWithDirection(o => o.MyColumnToOrderBy, o => o.SortingDirection)
would I then need to rewrite the methods? how?
- update -
by way of rationale, here is what I'm looking to accomplish:
Strike Type Price 98 Ask 101 98 Ask 100 98 Ask 99 98 Bid 95 98 Bid 96 98 Bid 97
as you can see, asks are sorted down but bids are sorted up such that the rows with the greatest difference are next to each other. so what I'd like to say is something like:
source.OrderBy(o => new { o.Strike, o.Type }) .ThenByWithDirection(o => o.Price, o => o.Type == "Ask" ? __down__ : __up__)
- update II -
a clumsy way to do this would be to issue two separate queries like this:
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)
and concatenate them
推荐答案
I don't have your entities/objects, but can you not just do something like:
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;
That is, create a new object that contains a single property by which you can perform a sort, and then use that in your ordering operations?