假设我有一个字符串的两份名单,List1
并且list2
,其中List1
的类型是一个对象的属性Foo
列表中fooList
.
Foo
如果没有字符串foo.List1
匹配list2
la 中的任何字符串,我想删除给定的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);
}
Run Code Online (Sandbox Code Playgroud)
是:
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 );
Run Code Online (Sandbox Code Playgroud)
基本上所有的魔法都发生在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 );
}
}
Run Code Online (Sandbox Code Playgroud)
然后我可以用一种更清晰的方式重写魔术线:
fooList.RemoveAll( x => x.List1.Intersect( list2 ).Empty() );
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
318 次 |
最近记录: |