两个列表都包含具有ID和名称属性的对象。
最终输出List3({4,马铃薯},{5,番茄})
答案 0 :(得分:1)
以下想法:
从基本列表中删除交集
IEnumerable<int> common = a.Intersect(b).ToList();
a.RemoveAll(x => common.Contains(x));
b.RemoveAll(x => common.Contains(x));
答案 1 :(得分:0)
您正在寻找symmetric difference
Dictionary<int, string> fruit = new Dictionary<int, string>() { { 1, "apple" }, { 2, "orange" }, { 3, "banana" }, { 4, "potato" }, { 5, "tomato" } };
Dictionary<int, string> fruit2 = new Dictionary<int, string>() { { 1, "apple" }, { 2, "orange" }, { 3, "banana" } };
var result = fruit.Values.Concat(fruit2.Values).Except(fruit.Values.Intersect(fruit2.Values));
我不确定保持身份证是否合理 因为也可能有这种情况
List1({1, apple}
和List2({1, potato}
答案 2 :(得分:0)
这个例子不包含对象,但它应该向您展示一种方法来实现您想要实现的目标
var list1 = new List<string>{"apple", "orange", "banana", "potato", "tomato"};
var list2 = new List<string>{"apple", "orange", "banana"};
var result = list1.Where(f => !list2.Contains(f));
答案 3 :(得分:0)
IEnumerable<T> list3 = list1.Except(list2);
如果两个列表中的对象相同(相同的对象引用),则此方法有效。如果它们仅相等但不相同,请考虑覆盖集合中对象类型的Equals运算符,或使用替代LINQ表达式,例如
IEnumerable<TypeWithId> set3 = set1.Where((item) => !set2.Any((item2) => item.id==item2.id));