查找序列号

时间:2011-12-02 13:36:49

标签: c# sql math coding-style

我有一组数字List<int>(例如):1,3,4,5,7,12,13,14,15,20,22,24,28,29,30

我希望将它们按顺序分组:

Sequence1 = from 1 amount 1 (1)
Sequence2 = from 3 amount 3 (3, 4, 5)
Sequence3 = from 7 amount 1 (7)
Sequence4 = from 12 amount 4 (12, 13, 14, 15)
Sequence5 = from 20 amount 1 (20)
Sequence6 = from 22 amount 1 (22)
Sequence7 = from 24 amount 1 (24)
Sequence8 = from 28 amount 3 (28, 29, 30)

我知道如何使用for和检查每个数字。是否有更优雅的方式或算法,或某些sql / lambda命令可以帮助我?

3 个答案:

答案 0 :(得分:5)

如果输入已排序,并且您确实想要避免foreach循环,则可以使用:

list.Select((value,index)=>new {value,index}).GroupBy(x=>x.value-x.index,x=>x.value).Select(g=>g.AsEnumerable())

还可以编写一般助手方法:

public static IEnumerable<IEnumerable<T>> SplitBetween<T>(this IEnumerable<T> sequence, Func<T,T,bool> predicate)
{
  T previous=default(T);
  List<T> list=new List<T>();
  int index=0;
  foreach(T current in sequence)
  {
    if((index>0)&&predicate(previous,current))
    {
      yield return list.ToArray();
      list.Clear();
    }
    list.Add(current);
    previous=current;
    index++;
  }
  if(list.Count>0)
    yield return list.ToArray();
}

然后将其与list.SplitBetween((previous,current) => previous+1 != current)

一起使用

答案 1 :(得分:3)

我不认为这是非常“优雅”,但这是我的建议,希望它可以帮助你:

var list = new List<int> { 1, 3, 4, 5, 7, 12, 13, 14, 15, 20, 22, 24, 28, 29, 30 };

int offset = 0;
int sequence = 0;
do
{
    int offset1 = offset;
    var subList = list.Skip(offset).TakeWhile((item, index) => (index == 0) || (item == (list[offset1 + index - 1] + 1))).ToList();
    offset += subList.Count();
    sequence++;
    Debug.WriteLine("Sequence {0} from {1} amount {2} ({3})", sequence, subList[0], subList.Count(), string.Join(" ", subList));
}
while (offset < list.Count);

答案 2 :(得分:0)

int n = 12;//your number
int x = list.IndexOf(n);
var result = list.Skip(x).TakeWhile((value, index) => value - index == n);