Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

filter a linq query based on the results of another query's results

Tags:

c#

linq

I am wanting to filter a linq query

I have 2 linq statements

The 1st gets all the stores I want and the 2nd is where I filter information based on the results found in the 1st query.

var stores = ctx.Stores.Where(ps => ps.ParentStoreID == parent.ParentStoreID && ps.StoreID!=storeID);

var query = (from a in ctx.TransactionTable
          from b in ctx.MappingTable.Where(x => x.TransactionId== a.TransactionId).DefaultIfEmpty()
             where a.StoreID!=storeID
                 select new
                           {
                              Transactions = a,
                              Mapping = b
                           }).ToList();

How do I add another where clause into my 2nd query to only return results where a.StoreId is contained within the stores result?

like image 872
Diver Dan Avatar asked Oct 10 '22 10:10

Diver Dan


1 Answers

Like this:

var stores = ctx.Stores.Where(ps => ps.ParentStoreID == parent.ParentStoreID && ps.StoreID!=storeID);

var query = (from a in ctx.TransactionTable
            from b in ctx.MappingTable.Where(x => x.TransactionId==a.TransactionId).DefaultIfEmpty()
            where a.StoreID!=storeID && stores.Select(s => s.StoreID).Contains(a.StoreID)
            select new
            {
                Transactions = a,
                Mapping = b
            }).ToList();

You can find more info here: Linq to Entities - SQL "IN" clause

like image 72
david.s Avatar answered Oct 13 '22 09:10

david.s