1

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

Foo如果没有字符串与la 中的foo.List1任何字符串匹配,我想删除给定的字符串。list2RemoveAll

我可以用嵌套的 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);
            }
4

1 回答 1

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() );
于 2013-10-02T01:33:17.820 回答