LINQ(或伪代码)按接近程度对项目进行分组 [英] LINQ (Or pseudocode) to group items by proximity
本文介绍了LINQ(或伪代码)按接近程度对项目进行分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有人能启发我如何使用LINQ(或在需要时更合适的方法)创建一个整数列表列表,这些列表按彼此的邻近程度分组.
Is anybody able to enlighten me on how to use LINQ (or something more appropriate if necessary) to create a list of lists of integers that are grouped by the the proximity from each other.
基本上,我想创建数字在任何其他数字的5以内的组.
Basically, I want to create groups where the numbers are within 5 of any other number.
所以,给定:
3 27 53 79 113 129 134 140 141 142 145 174 191 214 284 284
产生以下列表:
3
27
53
79
113
129 134
140 141 142 145
174
194
214
284 284
谢谢!
推荐答案
LINQ在滚动总和等方面不是很好.在这里,简单的foreach
循环更好:
LINQ is not very good at things like rolling sums etc. A simple foreach
loop is better here:
static IEnumerable<IEnumerable<int>> GroupByProximity(
this IEnumerable<int> source, int threshold)
{
var g = new List<int>();
foreach (var x in source)
{
if ((g.Count != 0) && (x > g[0] + threshold))
{
yield return g;
g = new List<int>();
}
g.Add(x);
}
yield return g;
}
示例:
var source = new int[]
{
3, 27, 53, 79, 113, 129, 134, 140, 141, 142, 145, 174, 191, 214, 284, 284
};
foreach (var g in source.GroupByProximity(5))
{
Console.WriteLine(string.Join(", ", g));
}
输出:
3
27
53
79
113
129, 134
140, 141, 142, 145
174
191
214
284, 284
这篇关于LINQ(或伪代码)按接近程度对项目进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文