使用LINQ或lambda删除从列表中的实例? [英] Remove instances from a list by using LINQ or Lambda?
问题描述
现在我来了一个舞台,让我的所有数据在缓存中(对象)的列表,我接下来我要做的就是从列表中删除一些实例。
Now I come a stage to get all my data as a list in cache(objects) and my next thing I have to do is to remove some instances from the list.
通常情况下,我会做删除这样的:
Normally, I would do removing like this:
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的和删除代码为:
To be more specific, I actually build or populate toBeRemvoedItems list of a dynamic class (not a formal defined class). For example, the T class is something like MyClass and codes for removing are:
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;
});
}
我试图寻找从MSDN IEnumerable接口remove()方法,但我找不到删除的方法()有(这一点是有道理的IEnumerable只是用于枚举)。在List类,有几个重载的删除(...)方法。我不知道是否有任何其他方式使用LINQ和Lambda表达式用来删除列表中的项目?
I tried to search for Remove() method in IEnumerable interface from MSDN, but I cannot find the method of Remove() there (it makes sense that IEnumerable is used just for enumeration). In List class, there are several overloaded Remove(...) methods. I am not sure if there any alternative ways to remove items from a list by using LINQ or Lambda expressions?
顺便说一句,我想过一种方法做一个查询针对一个列表以获得一个子集或者与其中的条件,如从一个列表中移动的物品类似一新的IEnumerable列表。不过,我更喜欢从我的缓存列表中删除项目,还有一些情况下,我只是不能在一个类中重置列表属性到一个新的列表(私定的例子)。
By the way, I thought about a way to do a query against a list to get a subset or a new IEnumerable list with Where conditions, similar as moving items from a list. However, I prefer to remove items from my cached list, and there some cases I just cannot reset list property in a class to a new list (private set for example).
推荐答案
您可以使用该方法的 removeall过
MyClass one; //initialize MyClass
list.RemoveAll(item => one.Value1 == item.Value1 && one.Value2 < item.Value2);
这篇关于使用LINQ或lambda删除从列表中的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!