【问题标题】:Compare two lists and generate new one with matching results C#比较两个列表并生成具有匹配结果的新列表 C#
【发布时间】:2014-08-04 11:03:19
【问题描述】:

大家好,我是一名初学计算机工程师,但遇到了一个小问题。

我正在尝试比较两个大小不同的列表(列表 A 和列表 B),并生成一个与列表 A 大小相同的新列表(列表 C),其中包含 C# 中两个列表的匹配结果。这里 - 让我用一个例子来解释一下。

例如有以下两个列表:

list A: "1", "2", "3", "4", "5", "6"
list B: "1", "4", "5"

我想要这个结果:

list C: "1", "null", "null", "4", "5", "null"

到目前为止,我已经尝试过这段代码:

List<string> C = new List<string>();

// nA is the length of list A & nB is the length of list B 
for (int x = 0; x < nA; x++)
{
     for (int y = 0; y < nB; y++)
     {
         if (listA[x] == listB[y])
         {
            listC.Add(lista[x]);
         }
         else
            listC.Add(null);
     }
}

我使用的代码没有做它应该做的事情。我究竟做错了什么?还有其他方法可以做我需要的吗?我需要一些帮助,我希望我的问题的解决方案也可以帮助其他人。我希望我已经说清楚了,希望你们能帮助我解决我的问题。非常感谢您的帮助。

非常感谢您的回答:)

【问题讨论】:

    标签: c# list


    【解决方案1】:

    您可以使用此 LINQ 查询:

    List<string> listC = listA
        .Select(str => listB.Contains(str) ? str : "null")
        .ToList();
    

    我会使用它,因为它更具可读性和可维护性。

    【讨论】:

    • 为您修复了三元组
    • @Mr.Engineer:你需要 framework >= 3.5 并在文件顶部添加using System.Linq;
    【解决方案2】:

    您正在为 B 中的 每个 不相等的值添加 null

    试试这个:

    List<string> C = new List<string>();
    
    // nA is the length of list A & nB is the length of list B 
    for (int x = 0; x < nA; x++)
    {
         boolean found = false;
         for (int y = 0; y < nB; y++)
         {
             if (listA[x] == listB[y])
             {
                listC.Add(lista[x]);
                found = true;
                break;
             }
         }
         if (!found)
            listC.Add(null);
    
    }
    

    【讨论】:

    • 看来这正是我想要的。谢谢哥们:)
    【解决方案3】:

    摆脱手动循环。我会使用查询。这个想法是将第二个列表中的项目加入到第一个列表中。如果连接失败,我们将发出null

    var results =
     from a in listA
     join b in listB on a equals b into j
     let b = j.SingleOrDefault()
     select b == null ? "null" : a;
    

    【讨论】:

      【解决方案4】:

      我认为你不需要内部循环,你只需要记下你在列表 b 中查看的当前索引,如果 listA 包含该项目,则增加它。请注意,这可能需要额外的错误处理

      int currentIdx = 0;
      
      for (int x = 0; x < nA; x++)
      {
           if (listA[x] == listB[currentIdx])
           {
              listC.Add(lista[x]);
              currentIdx++;
           }
           else
              listC.Add(null);     
      }
      

      【讨论】:

        猜你喜欢
        • 2020-07-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多