假设我有两个字符串列表List1
和list2
,其中List1
是列表Foo
中fooList
类型对象的属性
如果Foo
中没有字符串与foo.List1
和list2
中的任何字符串匹配,我想删除给定的RemoveAll
。
我可以使用嵌套的for循环执行此操作,但有一种方法可以使用单个灵活的LINQ表达式执行此操作吗?
冗长的代码,构建新列表而不是从现有列表中删除内容:
var newFooList = new List<Foo>
foreach (Foo f in fooList)
{
bool found = false;
foreach (string s in newFooList)
{
if (f.FooStringList.Contains(s))
{
found = true;
break;
}
}
if (found)
newFooList.Add(f);
}
答案 0 :(得分:5)
是:
var list2 = new List<string> { "one", "two", "four" };
var fooList = new List<Foo> {
new Foo { List1 = new List<string> { "two", "three", "five" } },
new Foo { List1 = new List<string> { "red", "blue" } }
};
fooList.RemoveAll( x => !x.List1.Intersect( list2 ).Any() );
Console.WriteLine( fooList );
基本上所有的魔法都发生在RemoveAll
中:这只删除了条目的List1
属性和list2
的交集(即重叠)为空的条目。
我个人认为!....Any()
构造难以阅读,所以我希望手头有以下扩展方法:
public static class Extensions {
public static bool Empty<T>( this IEnumerable<T> l,
Func<T,bool> predicate=null ) {
return predicate==null ? !l.Any() : !l.Any( predicate );
}
}
然后我可以用一种更清晰的方式重写魔术线:
fooList.RemoveAll( x => x.List1.Intersect( list2 ).Empty() );