How to compare 2 List<string> objects to get the missing value from the List<string>

…衆ロ難τιáo~ 提交于 2021-02-05 08:12:49

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!