【问题标题】:OrderBy a List<Tuple<int, int>> by Item2 onlyOrderBy a List<Tuple<int, int>> 仅按 Item2
【发布时间】:2019-09-25 12:36:54
【问题描述】:

我有一个清单:

List<Tuple<int, int>> MyList = new List<Tuple<int, int>>();

列表的值如下:

int   int
0     2
0     1
0     4
1     2
1     3
1     0
2     0
2     9
2     1
3     2
3     5
3     2

如何按Item2最高 值对list 进行排序,但保存Item1 的顺序?如下:

int   int
2     0
2     9*
2     1
3     2
3     5*
3     2
0     2
0     1
0     4*
1     2
1     3*
1     0

尝试使用MyList.OrderBy(x =&gt; x.Item2)但没有成功

【问题讨论】:

  • 所需的排序顺序是什么?该示例按 Item2 排序。除非你的意思是 find the max Item2 value per Item1 then order the tuples by the Max` 值?

标签: c# linq sorting


【解决方案1】:

如我所见,您想订购(不是单个项目):

带有Item1 == 2

group 排在第一位,因为此groupItem2 值(9)高于所有其他组; group Item1 == 1 是最后一个,它的最大Item2 值(3)是其他组中最小的

2     0
2     9*
2     1
...
1     2
1     3*
1     0

要订购,让我们试试GroupBy

var result = MyList
  .GroupBy(item => item.Item1)                               // groups
  .OrderByDescending(group => group.Max(item => item.Item2)) // are ordered
  .SelectMany(group => group);                               // then expanded

【讨论】:

  • 完美运行。这就是我需要的。感谢您的回答和解释!
猜你喜欢
  • 1970-01-01
  • 2011-06-07
  • 2018-01-25
  • 1970-01-01
  • 2016-05-23
  • 2014-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-03
相关资源
最近更新 更多