微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 如何对逗号分隔的字符串中项目的出现次数进行分组和计数

我有一个具有以下属性的Student类

public class Student
{
    public string Name{ get; set; }
    public string Subject { get; set; }
}

假设我们有一个像下面这样的学生名单

var students = new List<Student>();
students.Add(new Student { Name = "John",Subject = "Math"});
students.Add(new Student { Name = "Bob",Subject = "English,Math"});
students.Add(new Student { Name = "Jane",Subject = "Math,History,Art"});
students.Add(new Student { Name = "Jim",Subject = "English"});

我想按主题对学生进行分组并计算主题.

所以输出就是

Math,3
English,1
History 1
Art 1

如何使用linq实现结果?

解决方法

students.SelectMany(arg => arg.Subject.Split(new []{','})) // split the Subject-property on commas
        .Select(arg => arg.Trim()) // get rid of the whitespaces after commas
        .GroupBy(arg => arg) // you can inject an equality comparer here,to achieve case insenstive grouping
        .Select(arg => new
                       {
                         Subject = arg.Key,Count = arg.Count()
                       }); // Todo output these objects to your console..

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐