如何向List添加缺失的数字

时间:2017-05-19 03:53:08

标签: c# asp.net list

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

  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"

5 个答案:

答案 0 :(得分: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");
        }

答案 1 :(得分:0)

如果您的列表中有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++;
            }


如果您觉得将代码放在一起有任何问题,请告诉我

答案 2 :(得分:0)

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

        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++;
            }

        }

答案 3 :(得分:0)

        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 :(得分:0)

这有效:

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