查找序号
本文关键字:查找 | 更新日期: 2023-09-27 18:16:33
我有一组数字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命令,将帮助我吗?
如果输入是排序的,并且您确实希望避免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)
我不认为这是非常"优雅"的,但这是我的建议,希望它能帮助你:
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);
int n = 12;//your number
int x = list.IndexOf(n);
var result = list.Skip(x).TakeWhile((value, index) => value - index == n);