【问题标题】:How to merge values of two lists together如何将两个列表的值合并在一起
【发布时间】:2012-05-03 19:49:57
【问题描述】:

例如我有:

public static List<int> actorList = new List<int>();
public static List<string> ipList = new List<string>();

他们都有不同的项目。

所以我尝试使用 foreach 循环将值(字符串和 int)连接在一起:

  foreach (string ip in ipList)
    {
        foreach (int actor in actorList)
        {
            string temp = ip + " " + actor;
            finalList.Add(temp);
        }
    }

    foreach (string final in finalList)
    {
        Console.WriteLine(finalList);
    }

虽然回头看,这是非常愚蠢的,显然不会起作用,因为第一个 forloop 是嵌套的。

我对 finalList 列表的期望值:

actorListItem1 ipListItem1
actorListItem2 ipListItem2
actorListItem3 ipListItem3

等等..

因此,两个列表中的值相互连接 - 对应于它们在列表顺序中的位置。

【问题讨论】:

    标签: c# .net windows


    【解决方案1】:

    使用LINQ的ZIP函数

    List<string> finalList = actorList.Zip(ipList, (x,y) => x + " " + y).ToList();
    
    
    finalList.ForEach(x=> Console.WriteLine(x)); // For Displaying
    

    或将它们组合成一行

    actorList.Zip(ipList,(x,y)=>x+" "+y).ToList().ForEach(x=>Console.WriteLine(x));
    

    【讨论】:

      【解决方案2】:

      一些功能上的好处呢?

      listA.Zip(listB, (a, b) => a + " " + b)
      

      【讨论】:

        【解决方案3】:

        假设您可以使用 .NET 4,您想查看Zip extension method 和提供的示例:

        int[] numbers = { 1, 2, 3, 4 };
        string[] words = { "one", "two", "three" };
        
        // The following example concatenates corresponding elements of the
        // two input sequences.
        var numbersAndWords = numbers.Zip(words, (first, second) => first + " " + second);
        foreach (var item in numbersAndWords)
            Console.WriteLine(item);
        Console.WriteLine();
        

        在本例中,因为words 中没有“4”对应的条目,所以从输出中省略了它。在开始之前,您需要进行一些检查以确保集合的长度相同。

        【讨论】:

          【解决方案4】:

          遍历索引:

          for (int i = 0; i < ipList.Count; ++i)
          {
              string temp = ipList[i] + " " + actorList[i];
              finalList.Add(temp);
          }
          

          您可能还想在此之前添加代码以验证列表的长度是否相同:

          if (ipList.Count != actorList.Count)
          {
              // throw some suitable exception
          }
          

          【讨论】:

            【解决方案5】:
            for(int i=0; i<actorList.Count; i++)
            {
               finalList.Add(actorList[i] + " " + ipList[i]);
            }
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2023-01-03
              • 1970-01-01
              • 2020-01-23
              • 1970-01-01
              • 1970-01-01
              • 2021-10-13
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多