So I have a Blog object which has a list of tag objects (List<Tag>
).
I'm trying to create a method that takes a list of tags and returns a list of blogs that contain all the tags in the passed in list.
I was able to make a method that will return a list of blogs if it matches one tag, but not a list of tags.
to do that I have this
entities.Blogs.Where(b => b.Tags.Any(t => t.Name == tagName))
But I can't figure out how to do something like this
entities.Blogs.Where(b => b.Tags.Any(t => t.Name == tags[0] AND t.Name == tags[1] AND t.Name == tags[2] etc.......))
Is there any way to do this?
Thank you!
I'm using LINQ to Entities
Where Clause in Query Syntax: The where clause is used to filter the query according to the given condition. You can provide a condition to where clause using lambda expression or by using Func delegate type. Where clause supports query syntax in both C# and VB.Net languages.
Using the List object Contains method in the Where clause will create the IN T-SQL clause. The code snippet uses the Microsoft Northwind sample database using the Customers table as an example.
In a LINQ query, the first step is to specify the data source. In C# as in most programming languages a variable must be declared before it can be used. In a LINQ query, the from clause comes first in order to introduce the data source ( customers ) and the range variable ( cust ).
LINQ is a data querying API with SQL like query syntaxes. LINQ provides functions to query cached data from all kinds of data sources. The data source could be a collection of objects, database or XML files. We can easily retrieve data from any object that implements the IEnumerable<T> interface.
Logically, I think you want something like:
entities.Blogs.Where(b => tags.All(t => b.Tags.Any(bt => bt.Name == t)))
Alternatively:
HashSet<string> tagNames = new HashSet<string>(tags);
return entities.Blogs
.Where(b => tagNames.IsSubsetOf(b.Tags.Select(x => x.Name)));
If this is using LINQ to Entities, I doubt that this will work - but it should work if you're just using LINQ to Objects. Even then, it's not going to be terribly efficient. I suspect there's a more efficient way of doing things, but I can't immediately think of it... it feels like you want a join, but then it gets tricky again.
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