开发者

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 f开发者_JS百科kId, 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())


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() });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜