LINQ表达式,用于查找两个字符串数组之间是否存在任何匹配项

tac*_*cos 1 c# linq lambda

假设我有一个字符串的两份名单,List1并且list2,其中List1的类型是一个对象的属性Foo列表中fooList.

Foo如果没有字符串foo.List1匹配list2la 中的任何字符串,我想删除给定的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)

Eth*_*own 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 );
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)