Home > Mobile >  LINQ query to find items in a list from other list by item
LINQ query to find items in a list from other list by item

Time:11-30

I have code, it working fine, but now want change "sugar" to shopResources.Product : List shopResourceProduct> and find it by id. How can i do it? After that it should return the same ProductList

var usedProduct = await this.context.Clients
        .Where(r => r.AllowedProduct.Any(u => u.Product.Contains("sugar")))
        .Select(r => r)
        .ToListAsync(ct);

I have looked at other queries but I can find a close comparison to this with Linq. Any ideas or anywhere you can point me to would be a great help.

CodePudding user response:

If you're saying you know how to find a single product in a list of N products, but you now want to find 2 products in a list of N, the general pattern is:

var iWant = new T[] { some, things, here };

var result = listOfNThings.Where(thing => iWant.Contains(thing));

This is typically "upside down" compared to how you normally think about "finding something in the collection of things", which looks more like:

var result = listOfNThings.Where(thing => thing.Something == blah);

The "straight forward" way considers thing.Something is equal to .... The "upside down way considers listIWant.Contains(thing.Something) because there isn't a thing.Something.IsContainedWithin(listIWant) - this is a bit of a departure from SQL where we do say WHERE something IN (list,i,want)


Assuming that Client.AllowedProduct is a collection (and hence should really be called AllowedProducts) of an entity that maps a ClientId and a ProductId, you can ask for clients whose allowedproduct collection has any x where the x.ProductId is Contained in the list you want:

var iWant = new[] { 1, 6, 9, 22 }; //list of 4 productids I want

var productsWanted = await this.context.Clients
    .Where(c => c.AllowedProduct.Any(ap => iWant.Contains(ap.ProductId)))
    .ToListAsync(ct);
  • Related