gpt4 book ai didi

c# - 使用 LINQ 对数字序列进行无间隙分组

转载 作者:可可西里 更新时间:2023-11-01 03:12:21 26 4
gpt4 key购买 nike

有了这个数组 int[]{ 1, 2, 3, 4, 7, 8, 11, 15,16,17,18 };我如何转换为这个字符串数组 "1-4","7-8","11","15-18"

建议?林克?

最佳答案

var array = new int[] { 1, 2, 3, 4, 7, 8, 11, 15, 16, 17, 18 };

var result = string.Join(",", array
.Distinct()
.OrderBy(x => x)
.GroupAdjacentBy((x, y) => x + 1 == y)
.Select(g => new int[] { g.First(), g.Last() }.Distinct())
.Select(g => string.Join("-", g)));

public static class LinqExtensions
{
public static IEnumerable<IEnumerable<T>> GroupAdjacentBy<T>(
this IEnumerable<T> source, Func<T, T, bool> predicate)
{
using (var e = source.GetEnumerator())
{
if (e.MoveNext())
{
var list = new List<T> { e.Current };
var pred = e.Current;
while (e.MoveNext())
{
if (predicate(pred, e.Current))
{
list.Add(e.Current);
}
else
{
yield return list;
list = new List<T> { e.Current };
}
pred = e.Current;
}
yield return list;
}
}
}
}

关于c# - 使用 LINQ 对数字序列进行无间隙分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4681949/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com