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

标签 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。

最佳答案

使用字符串的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

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") 不返回任何结果。

关于c# - LINQ: ...Where(x => x.Contains(以 "foo"开头的字符串 )),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3916093/

相关文章:

c# - StreamWriter-“\”和“/”之间的区别

c# - 是否有内置函数来反转位顺序

javascript - Ajax 向 Controller 发送空字符串?

c# - asp.net core中的http客户端异常处理

c# - 使用匿名方法的 Linq

linq - 代码第一次接近错误: The specified type member 'xxxxx' is not supported in LINQ to Entities

c# - 单击按钮时运行代码隐藏代码的 Javascript

c# - 如何使用 Linq 将数据表过滤为数据表?

.net - Linq - 行未找到或更改

c# - 仅使用扩展方法在 Linq 中进行漂亮、干净的交叉连接