tags:

views:

129

answers:

5

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.

+7  A: 

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.

BrunoLM
+1 and accepted answer for the additional info and the case insensitive example. Thanks!
Dave
+7  A: 

Try this:

var postsWithFooTag = posts.Where(x => x.Tags.Any(y => y.StartsWith("foo")))
Coding Gorilla
+1  A: 

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

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

RexM
+1  A: 
var tag = "foo";
var postsWithFooTag = 
  posts.Where( p=> p.Tags.Any( t => t.StartsWith(tag)));
Philip Rieck
+1  A: 

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

GôTô