I have 2 lists. 1 is a collection of products. And the other is a collection of products in a shop.
I need to be able to return all shopProducts if the names match any Names in the products.
I have this but it doesn't seem to work. Any ideas?
var products = shopProducts.Where(p => p.Name.Any(listOfProducts.
Select(l => l.Name).ToList())).ToList();
I need to say give me all the shopproducts where name exists in the other list.
You could create an
IEqualityComparer<T>
that says products with equal names are equal.Then you can use this in the
Intersect
extension method.Try this please
You could use a join, for example:
A fuller guide on join is here.
For LINQ-to-Objects, if
listOfProducts
contains many items then you might get better performance if you create aHashSet<T>
containing all the required names and then use that in your query.HashSet<T>
has O(1) lookup performance compared to O(n) for an arbitraryIEnumerable<T>
.For LINQ-to-SQL, I would expect (hope?) that the provider could optimise the generated SQL automatically without needing any manual tweaking of the query.