[英]LINQ expression to find if there are any matches between two arrays of string
假設我有兩個字符串列表, List1
和list2
,其中List1
是列表fooList
中類型為Foo
的對象的屬性。
如果在foo.List1
中沒有字符串與list2
中的任何字符串匹配,則我想刪除給定的Foo
,而foo.List1
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);
}
是:
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() );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.