【问题标题】:use linq to group by and then run select query with where condition使用 linq 进行分组,然后使用 where 条件运行选择查询
【发布时间】:2015-10-27 20:17:52
【问题描述】:

我有一个类,OrderInfo 如下所示,

 class OrderInfo
 {
    string Product
    boolean NoIssues
 }

我有一个 OrderInfo 列表。我想做的是了解每个产品是否存在问题。所以下面是我的列表的一个例子。

 ProductList

 Product      NoIssues
 ABC          true
 ABC          true
 ABC          false
 ABC          true
 EFG          true
 EFG          true
 EFG          true
 EFG          true
 EFG          true

下面是我想要的结果。

Result      
ABC       false
EFG       true

所以我打算使用 LINQ 按产品分组以获得唯一的产品列表,然后循环遍历此列表以运行选择查询,在其中过滤 NoIssues = false。但是不确定如何执行此操作或这是否是最好的方法

 var res = (from ord in ProductList
            group ord by ord.Product).ToList()

所以我相信上面的代码会给我一个独特的产品列表,我可以循环访问。但不确定如果我使用带有 where 条件且不返回任何内容的 select 语句会发生什么?

【问题讨论】:

  • 为什么不将where 子句添加到主查询中?

标签: c# linq


【解决方案1】:

你可以使用All :-

List<OrderInfo> result = list.GroupBy(x => x.Product)
                             .Select(x => new OrderInfo
                                       {
                                           Product = x.Key,
                                           NoIssues = x.All(z => z.NoIssues)
                                       }).ToList();

或者,如果您更喜欢查询语法:-

List<OrderInfo> result = (from ord in ProductList
                         group ord by ord.Product into g
                         select new OrderInfo
                               {
                                    Product = g.Key,
                                    NoIssues = g.All(x => x.NoIssues)
                               }).ToList();

【讨论】:

    【解决方案2】:

    如果您不想为此创建新的 Product 对象,我会选择:

    var result = from product in ProductList
                 group product by product.Product into productGroup
                 select productGroup.Where(p => !p.NoIssues)
                                    .DefaultIfEmpty(productGroup.First())
                                    .First();
    

    否则,@Rahul Singh 的回答更直观。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-25
      • 1970-01-01
      • 1970-01-01
      • 2021-08-18
      • 2020-08-29
      • 1970-01-01
      • 2016-06-03
      • 2020-08-28
      相关资源
      最近更新 更多