简体   繁体   English

如何通过Linq分区然后按不同属性分组

[英]How to partition and then group by different properties through Linq

Suppose a class like this below 假设下面是一个这样的类

public class Student
{
    public string Name {get;set;}
    public string Topic {get;set;}
    public string Age {get;set;}
}

and a list like this 和这样的清单

var students = new List<Student>();

with data: 与数据:

Name           Topic       Age
S1             alpha       15
S2             beta        15
S3             gamma       17
S4             theta       16
S5             alpha       15
S6             alpha       17
S7             gamma       17
S8             theta       18
S9             alpha       19

..

I need to create a dataset like below out of the students list 我需要在students列表之外创建如下所示的数据集

Topic  15    16    17   18   19
alpha  2      0    1    0     1
beta   1      0    0    0     0
gamma  0      0    2    0     0
theta  0      1    0    1     0 

what is the best way to go about solving this without having to create a strongly typed dataset with properties 15,16.. 解决此问题的最佳方法是什么,而不必创建具有属性15,16的强类型数据集。

Is there a way I can partition my collection using linq to generate an anonymous datastructure like just above? 有没有一种方法可以使用linq对集合进行分区以生成像上面一样的匿名数据结构?

Also, was not sure on how to word the question, hence if you think title of the question is totally misleading, please suggest how can I improve the title 另外,不确定如何措词,因此,如果您认为问题的标题完全令人误解,请提出如何改善标题的建议

    Dictionary<string,IGrouping<int,Student>> partition = students.GroupBy(s=> s.Topic).
     ToDictionary(grp=> grp.Key, grp=> grp.GroupBy(g=> g.Age));

This will give you a dictionary of all Topics to a grouping by age a simple count on the grouping will give you the amount. 这将为您提供按年龄分组的所有主题的词典,只需对分组进行简单计数即可获得数量。 This is off the cuff without intellisense so you might need to fix a bad naming or 2 如果没有智能感知,这是袖手旁观,因此您可能需要修正错误的命名或2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM