2010-10-26 12 views
6

Quindi ho un oggetto Blog che ha un elenco di oggetti tag (List<Tag>).Come fare WHERE IN in linq

Sto provando a creare un metodo che prende un elenco di tag e restituisce un elenco di blog che contengono tutti i tag nell'elenco passato.

Sono riuscito a creare un metodo che restituirà un elenco di blog se corrisponde a un tag, ma non a un elenco di tag.

per farlo ho questa

entities.Blogs.Where(b => b.Tags.Any(t => t.Name == tagName)) 

Ma io non riesco a capire come fare qualcosa di simile

entities.Blogs.Where(b => b.Tags.Any(t => t.Name == tags[0] AND t.Name == tags[1] AND t.Name == tags[2] etc.......)) 

Esiste un modo per fare questo?

Grazie!

Sto usando LINQ to Entities

+0

Vuoi dire che stai cercando blog che contengano almeno un tag dall'array dei tag? O stai cercando di trovare blog che contengono tutti i tag dell'array di tag? – MerickOWA

+0

Penso che lo farà in modo che restituisca solo qualcosa che abbia un tag che corrisponda a tutto nel tuo elenco passato. – BlackICE

+0

Sto cercando di trovare blog che contengano tutti i tag dall'array dei tag – hanesjw

risposta

11

Logicamente, Penso che si desidera qualcosa di simile:

entities.Blogs.Where(b => tags.All(t => b.Tags.Any(bt => bt.Name == t))) 

alternativa:

HashSet<string> tagNames = new HashSet<string>(tags); 
return entities.Blogs 
       .Where(b => tagNames.IsSubsetOf(b.Tags.Select(x => x.Name))); 

Se questo sta usando LINQ to Entities, dubito questo funzionerà, ma dovrebbe funzionare se stai usando LINQ to Objects. Anche allora, non sarà terribilmente efficiente. Sospetto che ci sia un modo più efficiente di fare le cose, ma non posso pensarci subito ... sembra che tu voglia unirsi, ma poi diventa di nuovo complicato.

+0

Jon Skeet è l'UOMO! Grazie JS. La prima opzione ha funzionato alla grande. – hanesjw

1

si può fare qualcosa di simile:

List<Tag> tags = GetTags...; 
IQueryable<Blog> blogs = entities.Blogs; // start with all 
foreach(var tag in tags){ 
    var thisTag = tag; //this is needed to prevent a bug 
    blogs = blogs.Where(entry=>entry.Tags.Any(entryTag=>entryTag.TagId==thisTag.TagId)); 
} 
return blogs.OrderBy....; 

Questa catena volontà insieme alla clausole Where a richiedono che tutti i tag siano presenti per un blog da restituire.

Problemi correlati