使用GROUP BY LINQ获取每列的特定计数 [英] Get the specific count of each column using GROUP BY LINQ

查看:82
本文介绍了使用GROUP BY LINQ获取每列的特定计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用LINQ GroupBy获取列中每个项目的计数,但是没有得到预期的输出. 例子:

I want to get the count of each items in columns using LINQ GroupBy, however I don't get the expected output. Example :

 NAME      | Items | Items2
  1.ken    | asd   | zxc
  2.kent   | null  | zwe
  3.ken    | qwe   | null

预期输出:

NAME | Items | Items2
ken  |  2    |   1
kent |  0    |   1

代码:

var Data = Items.GroupBy(z => z.Name)
                .Select(s =>
                    new {
                        Name = s.Key,
                        Items = s.Count(q => q.Items),
                        Items2 = s.Count(x => x.Items2)
                    })
                .ToList();

上面的代码不起作用.

The above code does not work.

推荐答案

我认为null值会在预期输出的Count()中造成问题.因此,我建议您在Count()中添加一个条件以排除null值.因此您的查询将如下所示:

I think the null values create issues in Count() in the expected output. So I suggest you to add a condition in Count() to exclude null values. So your query will look like:

var Data = Items.GroupBy(z => z.Name)
                .Select(s => 
                    new
                    { 
                        Name = s.Key, 
                        Items = s.Count(q => q.Items != null),
                        Items2 = s.Count(x => x.Items2 != null)
                    })
                .ToList();

这篇关于使用GROUP BY LINQ获取每列的特定计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆