C#/ LINQ的成套得到与相邻 [英] C#/Linq get sets with adjacent

查看:192
本文介绍了C#/ LINQ的成套得到与相邻的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个有序列表像
0,1,2,6,7,10

I have an ordered list like 0,1,2, 6,7, 10

我要得到其中的数字递增套1。
我想第一个数字和数或系列。

I want to get the sets where the numbers are incremented by 1. I want the first number and the count or the series.

所以,我会得到结果
开始= 0,计数= 3结果
开始= 6,数= 2结果
开始= 10,数= 1

So I would get
start=0, count=3
start=6, count=2
start=10, count=1

我怎么能做到这一点在C#?

How can I do that in C#?

答案去我的感觉是最好的方式。 。可读性比对我来说性能更重要

The answer goes to what I feel is the nicest way. Readability is more important than performance for me.

推荐答案

定义一个简单的类来保存结果:

Defining a simple class to hold the results:

    private class Set
    {
        public int Start = 0;
        public int Count = 0;
    }

您可以使用的方法是这样的:

You can use a method like this:

    private static IEnumerable<Set> GetSets(List<int> src)
    {
        List<Set> rtn = new List<Set>();
        int previous = int.MaxValue;

        foreach (int i in src)
        {
            if (i == previous + 1)
            {
                rtn[rtn.Count - 1].Count += 1;
            }
            else
            {
                rtn.Add(new Set() { Start = i, Count = 1 });
            }

            previous = i;
        }

        return rtn;
    }



我不热衷于的魔法值int.MaxValue ,也可节省周围的第一次迭代额外的逻辑。

I'm not keen on the magic value of int.MaxValue, but it saves extra logic around the first iteration.

调用 GetSets(新名单< INT>(){0,1,2,6,7,10})正确给你所需要的结果。

Calling GetSets(new List<int>() { 0, 1, 2, 6, 7, 10 }) correctly gives the result you required.

这篇关于C#/ LINQ的成套得到与相邻的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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