[英]How to Remove elements from one List based another list's element and condition?
How to remove list items from list1
which mats condition with list2
items using LINQ without duplicates 如何从列表
list1
删除列表项,该列表项使用LINQ在条件与列表2项list2
情况下不重复
I know how to do it in simple foreach
way but i want the same using Linq
style single line code. 我知道如何以简单的
foreach
方式进行操作,但我希望使用Linq
样式的单行代码也能做到相同。
How to do it using Linq
? 如何使用
Linq
做到这一点?
Input list
输入清单
list1 = new List(){new object{id = 40},new object{id = 50},new object{id = 60}}
list2 = new List(){new object{id = 400},new object{id = 50},new object{id = 600}}
Expected Output should from
list1
预期输出应来自
list1
new object{id = 40},new object{id = 60}
您可以删除以下元素:
list1.RemoveAll(item => list2.Any(item2 => item.Key == item2.Key))
尝试这个:
var list = list1.RemoveAll(l => list2.Contains(l));
In other perspective, 换句话说,
var list1 = Provider.FillList<SomeType>();
var list2 = Provider.FillList<SomeType>();
list1.RemoveAll(n=> list2.Exists(o=> o.Key == n.Key));
You can also try 您也可以尝试
list1.addRange(list2)
then next line would be a simple list1.Distinct(X=>x.Key1).ToList();
OR simples would be 或简单将是
list1.Except(list2,IEqualityComparer);
You would need to implement the equals method for this to work though. 但是,您将需要实现equals方法才能使其工作。
Another way would be to implement the Union 另一种方式是实施联盟
var result = List1.Union(List2, myEqualityComparer);
which uses the same logic as the except one, there are a few ways to cheat the endresult using link, most of them inefficient and take long to compute 除了使用相同的逻辑外,还有几种方法可以使用链接来欺骗最终结果,其中大多数方法效率低下,计算时间长
I would solve this with a Join statement: 我可以用Join语句解决这个问题:
var l = list1.Join(list2, outer => outer.Key, inner => inner.Key, (inner, outer) => outer);
where outer
is list1 and inner
is list2. 其中
outer
是list1, inner
是list2。 The result is a list comprising all elements with the same Key
, assuming that Key
is a property of the elements. 结果是一个列表,其中包含具有相同
Key
所有元素,并假设Key
是元素的属性。
The following code worked for me: 以下代码为我工作:
var list1 = new List<a> { new a { id = 40 }, new a { id = 50 }, new a { id = 60 } };
var list2 = new List<a> { new a { id = 400 }, new a { id = 50 }, new a { id = 600 } };
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.