Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do WHERE IN in linq

Tags:

c#

linq

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

like image 720
hanesjw Avatar asked Oct 26 '10 18:10

hanesjw


People also ask

What is where in LINQ?

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.

Can we use in in LINQ?

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.

How do you query in LINQ?

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 ).

How does LINQ where work?

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.


1 Answers

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.

like image 143
Jon Skeet Avatar answered Nov 10 '22 11:11

Jon Skeet