日期:2014-05-20 浏览次数:20977 次
var list = new[] { new { id=1, name="a" }, new { id=1, name="a" }, new { id=2, name="b" }, new { id=3, name="c" }, new { id=3, name="c" }, new { id=2, name="b" }, new { id=2, name="b" }, }; var result = list.GroupBy(x => x.id).Select(g => new { id = g.Key, count = g.Count(), name = g.First(s => s.id == g.Key).name }); foreach (var r in result) Console.WriteLine("id:{0} name:{1} count:{2}", r.id, r.name, r.count);
------解决方案--------------------
取group的第一个元素.
var result = list.GroupBy(x => x.id).Select(g => new { id = g.Key, count = g.Count(), item = g.First() }); foreach (var r in result) Console.WriteLine("id:{0} name:{1} count:{2}", r.id, r.item.name, r.count);
------解决方案--------------------
public class Student { public int Id { get; set; } public string Name { get; set; } } protected void Page_Load(object sender, EventArgs e) { List<Student> studentList = new List<Student>(); studentList.Add(new Student { Id = 1, Name = "1" }); studentList.Add(new Student { Id = 2, Name = "2" }); studentList.Add(new Student { Id = 2, Name = "3" }); studentList.Add(new Student { Id = 3, Name = "4" }); studentList.Add(new Student { Id = 3, Name = "5" }); studentList.Add(new Student { Id = 3, Name = "6" }); studentList.Add(new Student { Id = 4, Name = "7" }); studentList.Add(new Student { Id = 5, Name = "8" }); studentList.Add(new Student { Id = 6, Name = "9" }); studentList.Add(new Student { Id = 7, Name = "10" }); var results = studentList.Select(o => new { Id = o.Id, Name = o.Name, Count = studentList.Where(s => s.Id == o.Id).Count() }); foreach (var item in results) { Response.Write(string.Format("Id={0},Name={1},Count={2}", item.Id, item.Name, item.Count)); Response.Write("<br/>"); } }