[英]C# Group by or something else?
我有一个我创建的 RGBComparison 类型的列表。 它具有欧几里得距离、id、本地 id 等作为变量。 在我按距离对列表进行排序后,我有一个像这样的 output;
1.35363 id=3 1.43554 id=2 1.4556 id=3 1.5 id = 35 1.6 id = 2
=======================================
等。它们是子图像与输入子图像的欧几里德距离(变量名称距离)。 我想通过保持原始顺序对它们进行分组。 考虑到图像 id 1 有 8 个距离(图像 id 1 是最近的距离,列表中的第一个)。 我想要一个 output 之类的
1.35363 id=3 1.4556 id=3 1.43554 id=2 1.6 id=2 1.5 id = 35 ....
有没有办法做到这一点? 此外,我只会从输入中走最多 5 个距离。 比如id 1在List中有8个子图距离,那么我只取前5个。后面我会在原图上展示这些子图。
我真的很感激任何帮助。
如果您的数据在列表distances
中,您可以使用OrderBy
/ GroupBy
、 Take
和最后SelectMany
的组合来展平结果列表:
var results = distances.OrderBy( x=> x.Id)
.GroupBy(x => x.Id)
.Select(g => g.OrderBy(x => x.Distance).Take(5))
.SelectMany(x => x)
.ToList() ;
要将每个 Id 的距离数限制为最大 5,您确实需要分组,还需要在分组之前使用OrderBy
来诱导分组保留的 Id 的正确顺序。
根据评论和澄清进行编辑:
var results = distances.GroupBy(x => x.Id)
.Select(g => g.OrderBy(x => x.Distance).Take(5))
.SelectMany(x => x)
.OrderBy( x=> x.Distance)
.ToList();
这应该会给你一个按距离排序的列表,任何 id 最多包含 5 个元素。
您可以使用 LINQ 轻松地对列表进行排序
var myRGBComparisonList = new List<RGBComparison>();
//... populate list somewhere
var sortedSequence = from rgbComparison in myRGBComparisonList
orderby rgbComparison.ID ascending, rgbComparison.Distance ascending
select rgbComparison;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.