给定以下类的集合:
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")
没有结果.
试试这个:
var postsWithFooTag = posts.Where(x => x.Tags.Any(y => y.StartsWith("foo")))
Run Code Online (Sandbox Code Playgroud)