问题
How do I use the "NOT IN" to get the missing data, to be added to "foo" List.
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...
}
回答1:
Use List.Except:
foo.AddRange(accessories.Except(foo));
From MSDN:
Except Produces the set difference of two sequences.
回答2:
You can use .Except() to get the difference between two sets:
var difference = accessories.Except(foo);
// difference is now a collection containing elements in accessories that are not in foo
If you then want to add those items to foo
:
foo = foo.Concat(difference).ToList();
回答3:
There's a LINQ method to do this for you, it looks like this; accessories.Except(foo);
回答4:
You can combine Concat
and Distinct
to do this:
foo = foo.Concat(accessories).Distinct().ToList();
Edit: Or Except
as others have pointed out, which seems to be the superior choice for this case.
回答5:
If you just want foo to be the distinct combination of all elements in foo and accessories (i.e., the union of the two lists),
List<string> foo = foo.Union(accessories).ToList();
来源:https://stackoverflow.com/questions/33763942/how-to-compare-2-liststring-objects-to-get-the-missing-value-from-the-liststr