LINQ:...其中(x => x.Contains(以``foo''开头的字符串)) [英] LINQ: ...Where(x => x.Contains(string that start with "foo"))
问题描述
给出以下类别的集合:
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.
使用字符串的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" }}
要使用StringComparison.OrdinalIgnoreCase
,请使用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")
不返回结果.
Given a collection of the following class:
public class Post
{
...
public IList<string> Tags { get; set; }
}
Is there an easy way to get all Post
s that contain a tag starting with "foo" using LINQ?
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
should now contain items 1 and 3 of posts
.
Use string's StartsWith
var postsWithFooTag = posts.Where(x => x.Tags.Any(y => y.StartsWith("foo")));
x.Any
will check if any element matches some condition. StartsWith
checks if the element starts with a certain string.
The above returned:
new Post { Tags = new[] { "fooTag", "tag" }},
new Post { Tags = new[] { "someTag", "fooBarTag" }}
To make it case insensitive
use StringComparison.OrdinalIgnoreCase
.
var postsWithFooTag = posts.Where(x => x.Tags.Any(y => y.StartsWith("FoO", StringComparison.OrdinalIgnoreCase)));
Returns:
new Post { Tags = new[] { "fooTag", "tag" }},
new Post { Tags = new[] { "someTag", "fooBarTag" }}
while StartsWith("FoO")
returns no results.
这篇关于LINQ:...其中(x => x.Contains(以``foo''开头的字符串))的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!