Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ: ...Where(x => x.Contains(string that start with "foo"))

Tags:

c#

linq

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.

like image 899
davehauser Avatar asked Oct 12 '10 15:10

davehauser


People also ask

How use contains in Linq?

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.

What is any () in Linq?

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.


3 Answers

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.

like image 113
BrunoLM Avatar answered Nov 15 '22 13:11

BrunoLM


Try this:

var postsWithFooTag = posts.Where(x => x.Tags.Any(y => y.StartsWith("foo")))
like image 20
CodingGorilla Avatar answered Nov 15 '22 15:11

CodingGorilla


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

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

like image 22
Rex Morgan Avatar answered Nov 15 '22 15:11

Rex Morgan