LINQ: …Where(x => x.Contains(string that start with “foo”))

前端 未结 5 960
南旧
南旧 2021-01-04 19:06

Given a collection of the following class:

public class Post
{
    ...
    public IList Tags { get; set; }
}

Is there an easy

5条回答
  •  攒了一身酷
    2021-01-04 19:31

    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.

提交回复
热议问题