按属性值从列表中移除的方法





2.00/5 (1投票)
有两个列表,如何从List1中移除所有List2的实例,通过匹配属性值?
引言
有两个泛型列表(List<MyClass>
),如何从List1
中移除所有List2
的实例,通过匹配一个属性?
这是设置。我有一个类
public class MyClass
{
public int MyValue { get; set; }
public int MyOtherValue { get; set; }
}
和两个列表
List<MyClass> list1 = new List<MyClass>();
list1.Add(new MyClass() { MyValue = 1, MyOtherValue = 10 });
list1.Add(new MyClass() { MyValue = 2, MyOtherValue = 20 });
list1.Add(new MyClass() { MyValue = 3, MyOtherValue = 30 });
list1.Add(new MyClass() { MyValue = 4, MyOtherValue = 40 });
List<MyClass> list2 = new List<MyClass>();
list2.Add(new MyClass() { MyValue = 2, MyOtherValue = 50 });
list2.Add(new MyClass() { MyValue = 3, MyOtherValue = 60 });
我想从list1
中移除所有与MyValue
属性匹配的list2
实例。
解决方案
方法 1:循环和 LINQ
list2.ForEach(l2 => { list1.RemoveAll(l1 => l1.MyValue == l2.MyValue); });
方法 2:LINQ 和循环
(from l1 in list1 join l2 in list2 on l1.MyValue equals l2.MyValue
select l1).ToList().ForEach(i => list1.Remove(i));
输出(来自两者)
MyValue: 1 MyOtherValue: 10
MyValue: 4 MyOtherValue: 40
性能
不要被Method1
可能看起来比Method2
更美观所迷惑。性能取决于列表的大小。当list2
的元素数量相对于list1
的大小来说较多时,Method1
的扩展性非常差。
List1 size: 1.000.000
{
List2 size: 10
Method 1: 103 ms
Method 2: 325 ms
List2 size: 100
Method 1: 5534 ms
Method 2: 682 ms
}
List1 size: 1.000
{
List2 size: 100
Method 1: 1 ms
Method 2: 11 ms
List2 size: 900
Method 1: 32 ms
Method 2: 12 ms
}
And it gets all bad when both lists are large:
List1 size: 100.000
{
List2 size: 90.000
Method 1: 297834 ms
Method 2: 7555 ms
}
结论
除非你确定要移除的列表相对于主列表来说非常小(小于 50 个元素),否则使用Method2
。
历史
- 2009-11-06:第一个版本