【问题标题】:How to add missing numbers to a List如何将缺失的数字添加到列表中
【发布时间】:2017-05-19 03:53:07
【问题描述】:

我有一个数组列表。其中包含以逗号分隔的月份数和数据。 现在我想遍历这个列表并检查是否缺少任何月份数。如果然后需要按顺序添加该月份数,数据部分为零。

  List<string> MyData = new List<string>();
  MyData.Add("4,500"); //dynamically adding. 4(april) and 6(june) are month numbers.
  MyData.Add("6,400");
  foreach (string str in MyData)
        {
  int GetmonthNum = Convert.ToInt32(str.Substring(0, str.IndexOf(',')));
        }

现在需要添加值为零的所有其他缺失月份数。结果列表应该是

"4,500","5,0","6,400","7,0","8,0","9,0","10,0","11,0","12,0","1,0","2,0","3,0"

【问题讨论】:

    标签: c# asp.net list


    【解决方案1】:

    你可以像这样使用contains

            var result = new List<string>();
            for (int i = 1; i <= 12 ; i++)
            {
                var firstMatch = myData.FirstOrDefault(x => x.Contains(i + ","));
    
                if (firstMatch == null)
                {
                    result.Add(i + ",0");
                }
                else
                {
                    result.Add(firstMatch);
                }
                // or short code: result.Add(firstMatch ?? i + ",0" );
            }
    

    如果你想“4,500”是第一项,那就试试吧

            var minMonth = myData.Min(x => Convert.ToInt32(x.Substring(0, x.IndexOf(",", StringComparison.CurrentCulture))));
    
            var result = new List<string>();
            for (int i = minMonth - 1; i < minMonth + 11; i++)
            {
                var firstMatch = myData.FirstOrDefault(x => x.StartsWith((i % 12) + 1 + ","));
                result.Add(firstMatch ?? (i % 12) + 1 + ",0");
            }
    

    【讨论】:

    • 有什么方法可以得到“4,500”、“5,0”、“6,400”、“7,0”、“8,0”、“9,0”的结果输出, "10,0","11,0","12,0","1,0","2,0","3,0" 格式?
    • 你想将List转换成字符串还是设置“4,500”为第一项?
    • 想将第一个项目设置为自身。然后按顺序重复其他月份。例如:如果第一项是 4 月。那么新的数组列表应该是从四月,五月,六月,...三月
    • @user2431727 当 minMonth 指定为 2(feb) 时,它无法正常工作。获取 2 月、3 月、4 月、5 月、4 月、7 月、5 月、9 月、10 月、11 月、12 月、1 月
    • 你的问题是什么? minMonth = 2 然后 feb 是第一项。或者你想要什么?
    【解决方案2】:

    如果您的列表中有 12 项 [相对于 12 个月],请尝试以下代码

    List<string> MyData = new List<string>();
                MyData.Add("4,500"); //dynamically adding. 4(april) and 6(june) are month numbers.
                MyData.Add("6,400");
                int i = 1;
                // use variable i from 1 to 12 as month indicator
                foreach (string str in MyData)
                {
                    string month = str.Substring(0, str.IndexOf(',')); 
                    // get the month from your list item here
                    int GetmonthNum = Convert.ToInt32( month==string.Empty || month==null ? i.ToString() : month  );
                   // here use conditional operator to check if month is not there in list item , if it is not present than return i as misisng month 
                    i++;
                }
    


    如果您在将代码放在一起时遇到任何问题,请告诉我

    【讨论】:

      【解决方案3】:
              List<string> MyData = new List<string>();
              MyData.Add("4,500"); 
              MyData.Add("6,400");
      
              var months = Enumerable.Range(1, 12);
              foreach (int month in months)
              {
                  if (MyData.Any(a =>  a.Split(',')[0] == month.ToString()))
                  continue;
                  MyData.Add(string.Format("{0},{1}", month.ToString(), "0"));
              }
      

      【讨论】:

        【解决方案4】:

        这行得通:

        MyData =
            MyData
                .Select(x => x.Split(',').Select(y => int.Parse(y)).ToArray())
                .Concat(Enumerable.Range(1, 12).Select(x => new [] { x, 0 }).ToArray())
                .OrderBy(x => x[0])
                .GroupBy(x => x[0], x => x[1])
                .SelectMany(x => x.Take(1), (y, z) => $"{y.Key},{z}")
                .ToList();
        

        这给出了:

        1,0 2,0 3,0 4,500 5,0 6,400 7,0 8,0 9,0 10,0 11,0 12,0

        【讨论】:

          【解决方案5】:

          我能够通过以下循环实现您想要的结果。不过有很多方法可以做到这一点。

          int arrayIndex = 0;
          int month = 1;
          
          for (int i = 0; i < 12; i++)
          {
              if (myArray[arrayIndex].Split(',')[0] == Convert.ToString(month))
              {
                  MyData.Add(myArray[arrayIndex]);
                  month++;
                  arrayIndex++;
              }
              else
              {
                  MyData.Add(Convert.ToString(month) + ",0");
                  month++;
              }
          
          }
          

          【讨论】:

            猜你喜欢
            • 2017-12-02
            • 2018-03-02
            • 1970-01-01
            • 1970-01-01
            • 2022-01-25
            • 1970-01-01
            • 2023-03-21
            • 2016-01-22
            • 2016-10-29
            相关资源
            最近更新 更多