我有两个字符串列表。如何获取它们之间的不同值列表或从第一个列表中删除第二个列表元素?
List<string> list1 = { "see","you","live"}
List<string> list2 = { "see"}
结果应该是{"you","live"}
。
我有两个字符串列表。如何获取它们之间的不同值列表或从第一个列表中删除第二个列表元素?
List<string> list1 = { "see","you","live"}
List<string> list2 = { "see"}
结果应该是{"you","live"}
。
在我看来你需要Enumerable.Except()
:
var differences = list1.Except(list2);
然后你可以遍历差异:
foreach(var difference in differences)
{
// work with each individual string here.
}
如果要从第一个列表中获取项目,第二个列表中的项目除外,请使用
list1.Except(list2)
如果要获取第一个列表或第二个列表中的项目,但不能同时获取两者,您可以使用
list1.Except(list2).Concat(list2.Except(list1))
这是我发现独特的好方法....
两个列表中的唯一
var A = new List<int>() { 1,2,3,4 };
var B = new List<int>() { 1, 5, 6, 7 };
var a= A.Except(B).ToList();
// outputs List<int>(2) { 2,3,4 }
var b= B.Except(A).ToList();
// outputs List<int>(2) { 5,6,7 }
var abint= B.Intersect(A).ToList();
// outputs List<int>(2) { 1 }
here is my answer,
find distinct value's in two int list and assign that vlaues to the third int list.
List<int> list1 = new List <int>() { 1, 2, 3, 4, 5, 6 };
List<int> list2 = new List<int>() { 1, 2, 3, 7, 8, 9 };
List<int> list3 = new List<int>();
var DifferentList1 = list1.Except(list2).Concat(list2.Except(list1));
foreach (var item in DifferentList1)
{
list3.Add(item);
}
foreach (var item in list3)
{
Console.WriteLine("Different Item found in lists are{0}",item);
}
Console.ReadLine();