views:

31

answers:

1

I have a simple table like:

| fkId | Item |
---------------
|    1 |    A |
|    1 |    B |
|    1 |    C |
|    1 |    D |
|    2 |    H |
|    2 |    I |
|    3 |    Y |
|    3 |    Z |

I want a LINQ query that will first count the number of Item's per fkId, and then report the number of fkId's with a given Item-count.

With the sample data, I want to know that I have 1x ID with 4x items, and 2x IDs with 2x Items

So, something like:

| ItemCount | fkIdsWithItemCount |
----------------------------------
|         4 |                  1 |
|         2 |                  2 |

I'm getting halfway there ("how many items per fkID") with:

MyTable
    .GroupBy(i => i.FkID)
    .Select(i => i.Count())
+4  A: 

You got halfway there with a .GroupBy — now you have to apply another .GroupBy to do the rest:

MyTable.GroupBy(i => i.FkID)
       .GroupBy(group => group.Count())
       .Select(group => new { ItemCount = group.Key,
                              FkIdsWithItemCount = group.Count() });
Timwi