简体   繁体   English

使用linq进行分组,然后使用where条件运行select查询

[英]use linq to group by and then run select query with where condition

I have a class, OrderInfo shown below, 我有一个类,如下所示的OrderInfo,

 class OrderInfo
 {
    string Product
    boolean NoIssues
 }

I have a list of OrderInfo. 我有一个OrderInfo列表。 What I would like to do is to know for each product if there is an issue or not. 我想做的是了解每种产品是否存在问题。 So below is an example of my list. 因此,以下是我的列表示例。

 ProductList

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

Below is the result I would like. 以下是我想要的结果。

Result      
ABC       false
EFG       true

So I was going to use LINQ to group by product to get a unique list of products and then loop through this list to run a select query where I filter on NoIssues = false. 因此,我将使用LINQ按产品分组以获取唯一的产品列表,然后遍历该列表以运行选择查询,在该查询中我根据NoIssues = false进行过滤。 However not sure how to do this or if this is the best way 但是不确定如何执行此操作,或者这是否是最佳方法

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

So I believe the code above will give me a unique list of products that I can loop through. 因此,我相信上面的代码将为我提供一个可以循环浏览的独特产品列表。 But not sure whats happens if I use a select statement with a where condition where nothing is returned? 但是不知道如果我在条件不返回任何内容的情况下使用select语句会发生什么情况?

You can use All :- 您可以使用全部

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

Or if you prefer query syntax:- 或者,如果您更喜欢查询语法:

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();

If you don't want to create new Product objects for this, I would go with: 如果您不想为此创建新的Product对象,则可以使用:

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

Otherwise, @Rahul Singh's answer is more intuitive. 否则,@ Rahul Singh的答案会更直观。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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