How can I use LINQ to summarize this data - the number of relationships grouped by the number of these relationships

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 need a LINQ query that will first count the number of Item per fkId and then report the number of fkId with the given number of elements.

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

So something like:

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

I get halfway ("number of elements per fkID") with:

MyTable
    .GroupBy(i => i.FkID)
    .Select(i => i.Count())
+3
1

.GroupBy - .GroupBy, :

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

Source: https://habr.com/ru/post/1762357/


All Articles