如何比较 2 个 List<string> 对象以从 List<string> 中获取缺失值

fle*_*sod 1 c# c#-4.0

如何使用“NOT IN”来获取缺失的数据,添加到“foo”列表中。

var accessories = new List<string>(); 
var foo = new List<string>();

accessories.Add("Engine");
accessories.Add("Tranny");
accessories.Add("Drivetrain");
accessories.Add("Power Window");

foo.Add("Engine");
foo.Add("Tranny");
foo.Add("Power Window");

foreach(var v in foo.Where(x => x??).???)
{
    foo.Add(v);  //Add the missing "Drivetrain" to it...
}
Run Code Online (Sandbox Code Playgroud)

Dav*_*vid 5

您可以使用.Except()来获取两组之间的差异:

var difference = accessories.Except(foo);
// difference is now a collection containing elements in accessories that are not in foo
Run Code Online (Sandbox Code Playgroud)

如果您想将这些项目添加到foo

foo = foo.Concat(difference).ToList();
Run Code Online (Sandbox Code Playgroud)


Ami*_*ich 5

使用List.Except

foo.AddRange(accessories.Except(foo));
Run Code Online (Sandbox Code Playgroud)

来自 MSDN:

except 产生两个序列的集合差。