【问题标题】:Get possible ranges of int collection [duplicate]获取可能的int集合范围[重复]
【发布时间】:2018-03-26 20:04:06
【问题描述】:

我有一个 id 列表 (int),例如

[1,2,3,5,7,8,11,13,14..]

是否有一种快速/智能的方式(linq?)来获取所有 id 或如果可能的话,范围? 结果应该类似于[1-3, 5, 7-8, 11, 13-14]。

当然,很容易循环并计算 int 值以获得结果,但我相信一定有更简单的方法来做到这一点。

【问题讨论】:

  • 生成范围的逻辑是什么?为什么不是 1-5、3-8 等?
  • 有没有快速/智能的方式(linq?) - 如果“快速”是指执行速度,那么“foreach”总是比 LINQ 快

标签: c# linq int range


【解决方案1】:

带有单个 for 循环的老式方法。

try
{
     List<int> i = new List<int>() { 1, 2, 3, 5, 7, 8, 11, 13, 14 };
     int istart = i[0];
     bool flag = false;
     // Use StringBuilder
     for(int index = 0;index<i.Count-1;index++)
     {
         if ((i[index] + 1) == i[index + 1])
         {
              flag = true;
              continue;
         }
         else
         {
              if (!flag)
                  Console.Write(istart);
              else
                  Console.Write(istart + "-" + i[index]);

              Console.Write(",");

              flag = false;
              istart = i[index + 1];
          }
      }
      if (istart + 1 == i[i.Count - 1])
          Console.Write(istart + "-" + i[i.Count - 1]);
      else
          Console.WriteLine(istart);
}
catch(Exception ex)
{
       Console.WriteLine(ex.Message);
}
Console.WriteLine();
Console.WriteLine("Done");
Console.Read();

输入List&lt;int&gt; i = new List&lt;int&gt;() { 1, 2, 3, 5, 7, 8, 11, 13, 14 };

输入List&lt;int&gt; i = new List&lt;int&gt;() { 1, 2, 3, 4, 5, 7, 8, 11, 13, 13 };

输入List&lt;int&gt; i = new List&lt;int&gt;() { 1, 4, 5, 7, 8, 9, 2, 13, 15, 17 };

【讨论】:

    【解决方案2】:

    有一种 linq 方法可以做到这一点(如果数字不重复),但我不确定它是否更容易:

    int last = -1;
    int rank = 0;
    IEnumerable<string> grouped = arr
        .GroupBy(i =>
        {
            rank += i - last - 1;
            last = i;
            return rank;
        })
        .Select(g => g.Count() == 1 ? g.First().ToString()
                    : g.First().ToString() + "-" + g.Last().ToString());
    

    对我来说,这似乎相当复杂,比必要的资源更密集,而且不灵活。 Linq 在很多情况下都很棒,但有时它并不适合。简单的循环有时是你能得到的最好的:

    IEnumerable<string> Group(IEnumerable<int> sortedArr)
    {
        using (var en = sortedArr.GetEnumerator())
        {
            if (!en.MoveNext())
            {
                yield break;
            }
            int first = en.Current;
            int last = first;
            int count = 1;
    
            while (true)
            {
                bool end;
                if ((end = !en.MoveNext()) || en.Current - last > 1)
                {
                    if (count == 1)
                    {
                        yield return first.ToString();
                    }
                    //else if (count == 2)
                    //{
                    //    yield return first.ToString();
                    //    yield return last.ToString();
                    //}
                    else
                    {
                        yield return first.ToString() + "-" + last.ToString();
                    }
                    if (end) { yield break; }
                    first = en.Current;
                    count = 1;
                }
                else
                {
                    ++count;
                }
                last = en.Current;
            }
        }
    }
    

    基准测试

    让我们测量一下 linq 在 10M 数组上的实际效率(低):

      simple loop:  328MB, 1.2sec
          my linq:  790MB, 2.7sec 
     Fredous linq:  1100MB, 7days (estimated)
    

    代码:

    int size = 10000000;
    int[] arr = new int[size];
    Random rnd = new Random(1);
    
    arr[0] = 0;
    for(int i = 1; i < size; ++i)
    {
        if (rnd.Next(100) < 25)
        {
            arr[i] = arr[i - 1] + 2;
        }
        else
        {
            arr[i] = arr[i - 1] + 1;
        }
    }         
    
    System.Diagnostics.Stopwatch st = new System.Diagnostics.Stopwatch();
    st.Start();
    var res = Group(arr).ToList();
    st.Stop();
    
    MessageBox.Show(st.ElapsedMilliseconds.ToString());
    MessageBox.Show(res.Sum(s => s.Length).ToString());// to be sure the work is done
    

    【讨论】:

    • 您也应该将实际的基准代码放在答案中;-)
    • @Fredou 好的,已添加
    • 我在回答中添加了一点免责声明 ;-)
    • @Fredou 我同意免责声明的前半部分,但不理解“你也应该做一个独特的”。
    【解决方案3】:

    免责声明 这在大名单上很慢,你也应该做一个独特的

    这应该可以解决问题

        static void Main(string[] args)
        {
            //a list with a possible of duplicate
            var theList = (new int[] { 1, 2, 3, 5, 7, 8, 11, 13, 14, 13 }).OrderBy(x => x).ToList();
    
            var step1 = theList.Select((a, b) =>  theList.Skip(b).TakeWhile((x, y) => a == x || theList[b + y] - 1 == theList[b + y - 1]));
    
            var step2 = step1.GroupBy(x => x.Last())
                             .Select(x => x.SelectMany(y => y).Distinct())
                             .Select(x => x.Count() > 1 ? string.Format("{0}-{1}", x.First(), x.Last()) : x.First().ToString());
    
    
            var result = string.Format("[{0}]", string.Join(", ", step2));
    
        }
    

    【讨论】:

      【解决方案4】:

      考虑到有序列表和唯一id,我认为最简单的方法是使用经典的for和while

      List<int> ids = new List<int>() { 1, 2, 3, 5, 7, 8, 11, 13, 14 };
                      int i = 0;
                      bool isrange;
      
                      for(i=0;i<ids.Count;i++)
                      {
                          isrange = false;
                          Console.Write(ids[i]);
      
                          while (i < ids.Count-1 && ids[i + 1] == ids[i] + 1)
                          {
                              i++;
                              isrange = true;
                          }
      
                          if (isrange)
                              Console.Write("-" + ids[i]);
      
                          if (!(i + 1 == ids.Count))
                              Console.Write(",");
                      }
      

      【讨论】:

        猜你喜欢
        • 2013-12-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-03
        • 2021-05-08
        • 1970-01-01
        • 2018-02-20
        • 1970-01-01
        相关资源
        最近更新 更多