LINQ:...其中(x => x.Contains(以``foo''开头的字符串)) [英] LINQ: ...Where(x => x.Contains(string that start with "foo"))

查看:79
本文介绍了LINQ:...其中(x => x.Contains(以``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 Posts 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 =&gt; x.Contains(以``foo''开头的字符串))的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆