简体   繁体   中英

Exclude LINQ results from one query in another LINQ query

I have two linq queries, querying two different entities. One entity contains all the warehouses, and another contains warehouses I don't need.

I use this query to get all the warehouses I don't need:

var sysproWarehouses = from i in sysproSession.Query<InvWarehouse>()
                            group i by i.Warehouse
                            into g
                            select new
                            {
                                g.Key 
                            };

This is the query where I want to get all the warehouses I do need:

var stockEvaluation = from ib in mapicsSession.Query<ItemBalance>()
                                  where //I guess it needs to be done here
                                  orderby w.Description
                                  group ib by w.Description
                                  into g
                                  select new
                                  {
                                      Warehouse = g.Key,
                                  };

Basically I just need to exclude the first query results from the second query. I apologise if this is a simple question, but I am a beginner so... Thank you!

Here is what you can do:

var sysproWarehouses = from i in sysproSession.Query<InvWarehouse>()
                            group i by i.Warehouse
                            into g
                            select new
                            {
                                g.Key 
                            };

var stockEvaluation = from ib in mapicsSession.Query<ItemBalance>()
                        orderby w.Description
                        group ib by w.Description
                        into g
                        select new
                        {
                            g.Key,
                        };

Now, exclude the sysproWarehouses list items from stockEvaluation list:

var result = stockEvaluation.Except(sysproWarehouses);

Note:- result contains the excluded items

I suppose you need an Except , but after the call to Select , as your two lists come from different tables. Something like this:

var stockEvaluation = (from ib in mapicsSession.Query<ItemBalance>()
                      orderby w.Description
                      group ib by w.Description
                      into g
                      select new
                      {
                          g.Key,
                      }).Except(sysproWarehouses);

Be aware that I also changed the only member within your anonymous type to match the type from your first query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM