去一个LIst中连续的几个数

View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace ListReturn
{


    /*偶尔看到的题目
     * Made By Anby
     * 我希望写一个方法,传入一个List<int>对象,然后处理返回一个string类型的值!
     * 只要流程是:假设传入的List<int>对象里面的值有{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18},则返回出的string为"1-18周",
     * 如果传入的List<int>对象里面的值有{1,2,3,4,5,7,8,9,10,11,15,16,17,18},则返回出的string为"1-5,7-11,15-18周"
     */
    class Program
    {
        static void Main(string[] args)
        {
            List<int> week=new List<int>();

            week.Add(1);
            week.Add(2);
            week.Add(3);
            week.Add(4);
            //week.Add(5);
            week.Add(6);
            week.Add(7);
            week.Add(8);
            //week.Add(9);
            week.Add(10);
            week.Add(11);
            week.Add(12);
            week.Add(13);
            week.Add(14);

            week.Sort();

            RT(week);
            Console.ReadLine();

        }
    
       static string Str = "";
        static void RT(List<int> week)
        {
            ArrayList Result = new ArrayList();
            for (int i = 1; i < week.Count; i++)
            {
                if (week[1] - week[0] == 1)
                    Result.Add(week[0]);
                if (week[i] - week[i-1] == 1)
                {
                    Result.Add(week[i]);
                    if (i == week.Count - 1)
                    {
                        Str += Result[0] + "-" + Result[Result.Count-1] + "周,";
                        Result.Clear();
                    }
                }
                else
                {
                    if (Result.Count > 0)
                    {
                        Str += Result[0] + "-" + Result[Result.Count-1] + "周,";
                        Result.Clear();
                    }
                    else
                    {
                        Str += Result[0] + "";
                        Result.Clear();
                    }

                }
            }
            Console.WriteLine(Str);
        }
    }
}
原文地址:https://www.cnblogs.com/anbylau2130/p/2721300.html