Dominic Järmann
Dominic Järmann

Reputation: 391

Linq: Get Item which is in a list which also is in a list

I'm currently trying to get a list of products which are in a list of stores but only if the product name is the same.

I always get 0 Items back.

I tried to solve to problem using two different approaches, which are below.

//First Approach, return 0
var stores= Store.ReadAll().Where(prods => 
prods.Products.Contains(product))

//Second Approach, doesn't compile but it shows what i wan't to do.

var stores= Store.ReadAll().Where(prods => 
prods.Products.Where(p => p.ProductName == productName));

Help appreciated :)

Upvotes: 1

Views: 101

Answers (3)

Sunil
Sunil

Reputation: 21406

Assuming stores is an IEnumerable type, then following should work. It's important to pass the second parameter to Contains method, so comparision is not case sensitive, else it will return nothing if case is different between product names.

I have assumed in my answer that Store type has a property called Products of List< string > type.

var matchingStores = stores.Where(s=> s.Products.Contains(productName,
                                                    StringComparer.OrdinalIgnoreCase));

Upvotes: 0

Dominic J&#228;rmann
Dominic J&#228;rmann

Reputation: 391

So i partly solved my problem and apparently, it wasn't really a linq problem, it was a database problem. I have a List of objects which contains a list of objects, which gives me a M:M relation. But the .net Entity Framework didn't regonize when i changed the list using list.add(item). So my list was always empty.

But anyway, thanks for the help ! :)

Upvotes: 0

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101681

What you are looking for is Any instead of Where:

var products = Store.ReadAll().Where(prods => prods.Products.Any(p => p.ProductName == productName));

Upvotes: 5

Related Questions