大家好我是一名初学计算机工程师,我有一点问题。
我试图比较两个不同大小的列表(列表A和列表B)并生成一个新的列表(列表C),其大小与列表A相同,包含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);
}
}
我使用的代码并没有做到它应该做的事情。我究竟做错了什么?还有另一种方法可以做我需要的吗?我需要一些帮助,我希望我的问题的解决方案也可以帮助别人。我希望我已经说清楚了,希望你们能帮我解决问题。我非常感谢你的帮助。
非常感谢答案:)
答案 0 :(得分:7)
您可以使用此LINQ查询:
List<string> listC = listA
.Select(str => listB.Contains(str) ? str : "null")
.ToList();
我会使用它,因为它更具可读性和可维护性。
答案 1 :(得分: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);
}
答案 2 :(得分: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;
答案 3 :(得分: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);
}