How to remove list items from list1
which mats condition with list2
items using LINQ without duplicates
I know how to do it in simple foreach
way but i want the same using Linq
style single line code.
How to do it using 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
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.
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:
var l = list1.Join(list2, outer => outer.Key, inner => inner.Key, (inner, outer) => outer);
where outer
is list1 and inner
is list2. The result is a list comprising all elements with the same Key
, assuming that Key
is a property of the elements.
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 } };
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.