简体   繁体   中英

Get the specific count of each column using GROUP BY LINQ

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

Expected output:

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

Code:

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.

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

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