Given a collection of the following class:
public class Post
{
...
public IList Tags { get; set; }
}
Is there an easy
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.
I believe this will work for what you're trying to do.
posts.Where(p => p.Tags.Any(t => t.StartsWith("foo")))
var tag = "foo";
var postsWithFooTag =
posts.Where( p=> p.Tags.Any( t => t.StartsWith(tag)));
Try this:
var postsWithFooTag = posts.Where(x => x.Tags.Any(y => y.StartsWith("foo")))
Try x => x.Tags.Any(tag => tag.StartsWith("foo"))