比较两个列表并生成一个包含匹配结果的新列表 C#

3

大家好,我是一个初学者的计算机工程师,我有一个小问题。

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

例如,有这两个列表:

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

And I want this result:

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

我使用的代码没有达到预期效果,我做错了什么?有没有其他方法可以实现我需要的功能?我需要一些帮助,希望解决我的问题也能帮助其他人。希望我表达清楚,也希望你们能帮我解决问题。非常感谢你们的帮助。

非常感谢回答 :)

4个回答

7
您可以使用以下LINQ查询:
List<string> listC = listA
    .Select(str => listB.Contains(str) ? str : "null")
    .ToList();

我会使用它,因为它更易读和易于维护。


已经为你修复了那个三元运算符。 - shree.pat18
@工程师:您需要框架>=3.5,并在文件顶部添加using System.Linq; - Tim Schmelter

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);

}

看起来这正是我想要的。谢谢伙计 :) - Mr. Engineer

0

远离手动循环。我会使用查询。思路是将第二个列表中的项连接到第一个列表中。如果连接失败,我们将发出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;

0

我认为你不需要内部循环,只需要记下你在列表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);     
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接