LINQ COUNT on multiple columns

后端 未结 3 1443
遇见更好的自我
遇见更好的自我 2021-01-12 15:14

If I have a table with a title column and 3 bit columns (f1, f2, f3) that contain either 1 or NULL, how would I write the LINQ to return the title with the count of each bit

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-12 16:02

    If you want to stick to a LINQ query and use an anonymous type, the query could look like:

     var query = 
          from r in ctx.myTable
          group r by r.title into rgroup
          select new
          {
              Title = rgroup.Key,
              F1Count = rgroup.Count(rg => rg.f1 == true),
              F2Count = rgroup.Count(rg => rg.f2 == true),
              F3Count = rgroup.Count(rg => rg.f3 == true)
          };
    

    The trick is to recognize that you want to count the number of true fields (it gets mapped as a nullable bool), which you can do with the Count operator and a predicate. More info on the LINQ group operator here: The Standard LINQ Operators

提交回复
热议问题