方向取决于数据时的OrderByWithDirection [英] OrderByWithDirection when direction depends on data

查看:96
本文介绍了方向取决于数据时的OrderByWithDirection的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此SO文章中: ascending/LINQ中的降序-可以通过参数更改顺序吗?提出了一种解决方案,该方法用于有条件地按升序或降序排序.

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)?

我似乎做不到:

source.OrderByWithDirection(o => o.MyColumnToOrderBy, o => o.SortingDirection)

然后我需要重写方法吗?怎么样?

would I then need to rewrite the methods? how?

-更新-

根据原理,这是我要完成的工作:

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__)

-更新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)

并连接它们

推荐答案

我没有您的实体/对象,但您不能只做类似的事情吗?

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?

这篇关于方向取决于数据时的OrderByWithDirection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆