c# - LINQ with Where and All 不过滤数据 - 这个查询有什么问题?

标签 c# visual-studio-2010 linq entity-framework .net-4.0

这是我遇到问题的代码。我正在使用从现有数据库建模的 EDMX。

// All orders completely shipped Grouped by RefId

                var RefIdsWithAllShippedOrders = mydbcontext.OrderDetails
                    .Where(s => s.Application.CustomerID == "MSFT")
                    .GroupBy(o => o.RefId)
                    .Where(t => t.All(i => i.Status.Description.ToUpper() == "SHIPPED"))
                    .Select(g => g.Key);

   // Iterate through the RefIds
    foreach (var refid in RefIdsWithAllShippedOrders)
                {

               // Gather all the orders that have the same RefIds
               var OrdersForThisRefid = (from o in mydbcontext.OrderDetails
                                        where o.RefId == refid
                                        select o).AsEnumerable();

 //gather all the orders with at least one Canadian recipient
 var orderswithcandianrecipients  = from o in OrdersForThisRefId
                                   where o.OrderRecipients.All( w=> w.Country.Trim().ToUpper() == "CANADA") // ****                                            
                                   select o;
             // Print RefIds of the orders that have at least one Canadian recipient
             foreach (var eachorder in orderswithcandianrecipients)
             {
                  Console.WriteLine(eachorder.RefId);
             }

      }

这是我的架构:

订单详情

 RefId      OrderId (PK)
 ABC001     00001
 ABC001     00002
 ABC001     00003
 ABC002     00004
 ABC002     12355

订单收件人

 PK     OrderID (FK)    NAME         COUNTRY
 1      00001           LINCOLN      USA
 2      00001           JEFFERSON    USA
 3      00001           WASHINGTON   CANADA
 4      00001           FRANKLIN     USA
 5      00002           GRANT        USA
 6      00002           WILSON       USA
 7      12355           FORD         CANADA
 8      12355           JOHNSON      USA

我希望得到的结果是 var 类型,其中包含至少有一个加拿大收件人的订单。在上面的示例中,这将是 OrderID = 00001 和 12355 的订单

代码,它似乎不尊重我用 * 标记的 WhereAll 过滤器。它返回所有订单。请帮助我了解我做错了什么。太感谢了。

最佳答案

我认为您需要Any 而不是All。通过使用 All,您表示订单上的所有收件人都必须是加拿大人。 Any 将为您提供至少有一位加拿大收件人的订单。

关于 All 的另一个警告。它不会寻找所有通过条件的项目,它会寻找第一个不符合条件的项目。因此,如果您有零个项目,则没有任何项目不符合条件,All 将始终返回 true

关于c# - LINQ with Where and All 不过滤数据 - 这个查询有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8929495/

相关文章:

c# - 未在自定义凭据上设置 WCF 证书

c# - 如何使用 C# 使用计时器捕获屏幕?

c# - Lambda表达式问题

c# - 动态编译 LINQ 查询以验证字典值

c# - 寻求解释/信息 : Windows write I/O performance with "fsync" (FlushFileBuffers)

c# - 对相同类型的 Func 使用三元运算符需要进行强制转换

c - 当我使用多个字符串时函数 sscanf_s 失败

c# - 如何检查 cshtml 中的 null/empty 值

visual-studio-2010 - 在 vs2010 中找不到一个好的干净方法来增加每个版本的文件版本

c# - LINQ:使用 Lambda 表达式获取 CheckBoxList 的所有选定值