Given a collection of the following class:
public class Post
{
...
public IList<string> Tags { get; set; }
}
Is there an easy way to get all Post
s 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
.
The Linq Contains Method in C# is used to check whether a sequence or collection (i.e. data source) contains a specified element or not. If the data source contains the specified element, then it returns true else return false.
The Any operator is used to check whether any element in the sequence or collection satisfy the given condition. If one or more element satisfies the given condition, then it will return true. If any element does not satisfy the given condition, then it will return false.
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.
Try this:
var postsWithFooTag = posts.Where(x => x.Tags.Any(y => y.StartsWith("foo")))
I believe this will work for what you're trying to do.
posts.Where(p => p.Tags.Any(t => t.StartsWith("foo")))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With