现在,我进入了一个阶段,将所有数据作为缓存(对象)中的列表获取,接下来要做的就是从列表中删除一些实例。
通常,我会像这样删除:
List<T> list;
List<T2> toBeRemovedItems;
// populate two lists
foreach(T2 item in toBeRemovedItems)
{
list.Remove(delegate(T one) {
// build a condition based on item
// return true or false
});
}
更具体地说,我实际上构建或填充动态类(不是正式定义的类)的 toBeRemvoedItems 列表。例如,T类类似于MyClass,删除代码为:
class MyClass<C> {
public string Value1 { get; set; }
public int Value2 { get; set; }
public C ObjectC { get; set; }
}
....
List<MyClass<C>> list;
// populate list
// populate toBeRemovedItems. Here is an example of hard-coded codes:
var toBeRemovedLItems = new[] {
new { Value1="a", Value2 = 1},
new { Value2="x", Value2 = 10},
...
};
// toBeRemovedItems may be the result of Select from a collection
foreach(var item in toBeRemovedLItems)
{
list.Remove(delegate(MyClass one) {
return one.Value1 = item.Value1 && one.Value2 < item.Value2;
});
}
我试图寻找Remove()
中的方法IEnumerable
来自MSDN的接口,但我找不到方法Remove()
在那里(这是有道理的IEnumerable
仅用于枚举)。在List类中,有几个重载的Remove(...)
方法。我不确定是否有其他方法可以使用 LINQ 或 Lambda 表达式从列表中删除项目?
顺便说一句,我想到了一种对列表进行查询以获取子集或新的方法IEnumerable
带有Where 条件的列表,类似于从列表中移动项目。但是,我更喜欢从缓存列表中删除项目,并且在某些情况下我无法将类中的列表属性重置为新列表(例如私有集)。
你可以使用该方法移除所有:
MyClass one; //initialize MyClass
list.RemoveAll(item => one.Value1 == item.Value1 && one.Value2 < item.Value2);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)