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

时间:2013-10-02 01:25:42

标签: c# linq lambda

假设我有两个字符串列表List1list2,其中List1是列表FoofooList类型对象的属性

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

1 个答案:

答案 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() );