我如何使用LINQ汇总此数据-按这些关系的数量分组的关系数 [英] How can I use LINQ to summarize this data--number of relationships grouped by the count of those relationships

查看:50
本文介绍了我如何使用LINQ汇总此数据-按这些关系的数量分组的关系数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的表,例如:

I have a simple table like:


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

我想要一个LINQ查询,该查询将首先计算每个fkId的Item数量,然后报告具有给定Item-count的fkId的数量.

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.

对于样本数据,我想知道我有1x个ID(含4个项目)和2x个ID(含2个项目)

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

所以,像这样:


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

我到了一半(每个fkID有多少个物品"),

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

MyTable
    .GroupBy(i => i.FkID)
    .Select(i => i.Count())

推荐答案

您已经有了.GroupBy到一半了—现在您必须应用另一个.GroupBy来完成其余工作:

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

这篇关于我如何使用LINQ汇总此数据-按这些关系的数量分组的关系数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆