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
StartsWithx.Anywill check if any element matches some condition.StartsWithchecks if the element starts with a certain string.The above returned:
To make it case
insensitiveuseStringComparison.OrdinalIgnoreCase.Returns:
while
StartsWith("FoO")returns no results.