我有一个具有以下属性的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 举报,一经查实,本站将立刻删除。