LINQ:... Where(x => x.Contains(以"foo"开头的字符串))

dav*_*ser 10 c# linq

给定以下类的集合:

public class Post
{
    ...
    public IList<string> Tags { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

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

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]);
Run Code Online (Sandbox Code Playgroud)

postsWithFooTag现在应该包含第1项和第3项posts.

Bru*_*oLM 17

使用字符串 StartsWith

var postsWithFooTag = posts.Where(x => x.Tags.Any(y => y.StartsWith("foo")));
Run Code Online (Sandbox Code Playgroud)

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

以上回复:

new Post { Tags = new[] { "fooTag", "tag" }},
new Post { Tags = new[] { "someTag", "fooBarTag" }}
Run Code Online (Sandbox Code Playgroud)

使它成为案例insensitive使用StringComparison.OrdinalIgnoreCase.

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

返回:

new Post { Tags = new[] { "fooTag", "tag" }},
new Post { Tags = new[] { "someTag", "fooBarTag" }}
Run Code Online (Sandbox Code Playgroud)

虽然StartsWith("FoO")没有结果.


Cod*_*lla 8

试试这个:

var postsWithFooTag = posts.Where(x => x.Tags.Any(y => y.StartsWith("foo")))
Run Code Online (Sandbox Code Playgroud)