Bronzato
Bronzato

Reputation: 9342

Linq query to return unique values inside a specific field

I have a basic classt(Entity Framework) named Post as is:

Public class Post
{
    Public int Id { get; set; }
    Public string Description { get; set; }
    Public string Tags { get; set; }
}

The Tags property contains a list of tags for the post (comma separated).

Is it possible to have a Linq which return all different tags present in the Post entity?

So for example if I have:

The result should be: java, cobol, foxpro, sybase, csharp

Thank you very much for your help.

Upvotes: 0

Views: 180

Answers (2)

Steve Ruble
Steve Ruble

Reputation: 3895

You aren't going to be able to do this in one step, because the things you need to do to split and recombine the comma-separated string aren't exposed through LINQ to Entities. You'll need to pull back the data first, then process the tags.

var tags = db.Posts.Select(p => p.Tags)
             .Distinct() // let SQL save us a little work, if some posts have same sets of tags
             .ToList()   // this causes the query to execute
             .SelectMany(t => t.Split(',')) // this happens client-side
             .Distinct();

Upvotes: 2

recursive
recursive

Reputation: 86084

You can do that using Split() and SelectMany().

posts.SelectMany(x => x.Tags.Split(',')).Distinct()

Upvotes: 2

Related Questions