LINQ找到一系列连续的数字 [英] LINQ to find series of consecutive numbers

查看:222
本文介绍了LINQ找到一系列连续的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个整数列表。我想找到名单上的连续编号,由起始索引和长度定义的所有运行。因此,例如,对于 [1,2,3,5,7,8] ,输出会 [{1,3输入列表},{5,1},{7,2}] 。这是很容易使用一个循环,像这样(未经测试的伪代码)的东西,做的:

I have a list of integers. I want to find all runs of consecutive numbers on that list, defined by the start index and length. So for example, for input list of [1,2,3,5,7,8], the output would be [{1,3}, {5,1}, {7,2}]. This is easy enough to do using a loop, something like this (untested pseudocode):

for(i=1, i < maxNum; i++)
{
  number = list[i];
  previousNumber = list[i-1];
  if(number - previousNumber == 1)
  {
    runLength++;
  }
  else
  {
    result.Add(startingNumber, runLength);
    runLength = 1;
    startingNumber = number;
  }
}



但我认为这将有可能使用LINQ to做。任何想法如何做到这一点?

But I thought it would be possible to do using LINQ. Any ideas how to do that?

推荐答案

一个linqish方式,可以的写一个扩展方法 GroupWhile 象下面这样(所有支票省略不优化,以容易理解。)

A linqish way can be writing an extension method GroupWhile like below (All checks omitted. not optimized to understand easily.)

int[] list = new int[] { 1, 2, 3, 5, 7, 8 };
var result = list.GroupWhile((x, y) => y - x == 1)
                 .Select(x => new {i = x.First(), len = x.Count()  })
                 .ToList();







public static IEnumerable<IEnumerable<T>> GroupWhile<T>(this IEnumerable<T> seq, Func<T,T,bool> condition)
{
    T prev = seq.First();
    List<T> list = new List<T>() { prev };

    foreach(T item in seq.Skip(1))
    {
        if(condition(prev,item)==false)
        {
            yield return list;
            list = new List<T>();
        }
        list.Add(item);
        prev = item;
    }

    yield return list;
}



TODO >:)

TODO: use IGrouping :)

这篇关于LINQ找到一系列连续的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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