Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use LINQ to summarize this data--number of relationships grouped by the count of those 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 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())
like image 275
STW Avatar asked Nov 24 '25 16:11

STW


1 Answers

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() });
like image 91
Timwi Avatar answered Nov 27 '25 04:11

Timwi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!