LINQ:...其中(x => x.Contains(以“foo”开头的字符串))

时间:2010-10-12 15:08:26

标签: c# linq

给出以下类的集合:

public class Post
{
    ...
    public IList<string> Tags { get; set; }
}

是否有一种简单的方法可以使用LINQ获取包含以“foo”开头的标记的所有Post

var posts = new List<Post>
{
    new Post { Tags = new[] { "fooTag", "tag" }},
    new Post { Tags = new[] { "barTag", "anyTag" }},
    new Post { Tags = new[] { "someTag", "fooBarTag" }}
};

var postsWithFooTag = posts.Where(x => [some fancy LINQ query here]);

postsWithFooTag现在应包含posts的第1项和第3项。

5 个答案:

答案 0 :(得分:16)

使用字符串StartsWith

var postsWithFooTag = posts.Where(x => x.Tags.Any(y => y.StartsWith("foo")));

x.Any将检查是否有任何元素符合某些条件。 StartsWith检查元素是否以某个字符串开头。

以上回复:

new Post { Tags = new[] { "fooTag", "tag" }},
new Post { Tags = new[] { "someTag", "fooBarTag" }}

要使案例insensitive使用StringComparison.OrdinalIgnoreCase

var postsWithFooTag = posts.Where(x => x.Tags.Any(y => y.StartsWith("FoO", StringComparison.OrdinalIgnoreCase)));

返回:

new Post { Tags = new[] { "fooTag", "tag" }},
new Post { Tags = new[] { "someTag", "fooBarTag" }}

StartsWith("FoO")没有返回任何结果。

答案 1 :(得分:8)

试试这个:

var postsWithFooTag = posts.Where(x => x.Tags.Any(y => y.StartsWith("foo")))

答案 2 :(得分:2)

我相信这对你想要做的事情有用。

posts.Where(p => p.Tags.Any(t => t.StartsWith("foo")))

答案 3 :(得分:2)

var tag = "foo";
var postsWithFooTag = 
  posts.Where( p=> p.Tags.Any( t => t.StartsWith(tag)));

答案 4 :(得分:2)

尝试x => x.Tags.Any(tag => tag.StartsWith("foo"))