小编典典

使用LINQ对没有空格的数字序列进行分组

c#

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

建议?LINQ?


阅读 252

收藏
2020-05-19

共1个答案

小编典典

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;
            }
        }
    }
}
2020-05-19