使用 LINQ 将数字序列分组而没有间隙 [英] Use LINQ to group a sequence of numbers with no gaps

查看:27
本文介绍了使用 LINQ 将数字序列分组而没有间隙的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

With this array int[]{ 1, 2, 3, 4, 7, 8, 11, 15,16,17,18 }; How can i convert to this string array "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;
            }
        }
    }
}

这篇关于使用 LINQ 将数字序列分组而没有间隙的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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