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

前端 未结 5 948
南旧
南旧 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.

    0 讨论(0)
  • 2021-01-04 19:32

    I believe this will work for what you're trying to do.

    posts.Where(p => p.Tags.Any(t => t.StartsWith("foo")))

    0 讨论(0)
  • 2021-01-04 19:33
    var tag = "foo";
    var postsWithFooTag = 
      posts.Where( p=> p.Tags.Any( t => t.StartsWith(tag)));
    
    0 讨论(0)
  • 2021-01-04 19:36

    Try this:

    var postsWithFooTag = posts.Where(x => x.Tags.Any(y => y.StartsWith("foo")))
    
    0 讨论(0)
  • 2021-01-04 19:44

    Try x => x.Tags.Any(tag => tag.StartsWith("foo"))

    0 讨论(0)
提交回复
热议问题