LINQ COUNT on multiple columns

后端 未结 3 1410
遇见更好的自我
遇见更好的自我 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:03

    Here's the solution I came up with. Note that it's close to the solution proposed by @OdeToCode (but in VB syntax), with one major difference:

    Dim temp = _
        (From t In context.MyTable _
         Group t.f1, t.f2, t.f3 By t.title Into g = Group _
         Select title, g).ToList
    
    Dim results = _
        From t In temp _
        Select t.title, _
            f1_count = t.g.Count(Function(x) If(x.f1, False)), _
            f2_count = t.g.Count(Function(x) If(x.f2, False)), _
            f3_count = t.g.Count(Function(x) If(x.f3, False))
    

    The first query does the grouping, but the ToList gets the grouped data as-is from the server. Eliminating the counting here keeps the resulting SQL statement from producing sub-SELECTs for each count. I do the counting in the second query locally.

    This works since I know the first query will return a manageable number of rows. If it were returning millions of rows, I'd probably have to go in another direction.

提交回复
热议问题