<?xml version="1.0" encoding="utf-8"?> <users> <user> <id>003</id> <name>小张</name> <sex>female</sex> <age>30</age> <university>南大</university> <phone>13328981152</phone> </user> <user> <id>004</id> <name>徐越</name> <sex>female</sex> <age>22</age> <university>一个大学</university> <phone>13328981152</phone> </user> <user> <id>005</id> <name>小樱</name> <sex>female</sex> <age>22</age> <university>南大</university> <phone>13328981152</phone> </user> <user> <id>006</id> <name>小赵</name> <sex>female</sex> <age>22</age> <university>南邮</university> <phone>13328981152</phone> </user> <user> <id>007</id> <name>小虎</name> <sex>female</sex> <age>22</age> <university>东南</university> <phone>13328981152</phone> </user>
/// <summary> /// 按学校分组 /// </summary> /// <returns></returns> public DataTable GroupBySchool() { List<ChartCount> listcount = new List<ChartCount>(); doc = XDocument.Load(path); // 计数 var users = (from u in doc.Element("users").Elements("user") group u by u.Element("university").Value into g select new { g.Key, Num=g.Count() }); foreach (var user in users) { ChartCount cc = new ChartCount(); cc.School = user.Num; cc.Count = user.Key; listcount.Add(cc); } return CollectionHelper.ToDataTable(listcount, null); } 那么我在分组的时候想要获得一些基本信息怎么办呢? /// <summary> /// 按学校分组 /// </summary> /// <returns></returns> public DataTable GroupBySchool() { List<ChartCount> listcount = new List<ChartCount>(); doc = XDocument.Load(path); // 计数 var users = (from u in doc.Element("users").Elements("user") group u by u.Element("university").Value into g select new { Id=g.Select(u=>u.Element("id").Value), Name=g.Select(u=>u.Element("name").Value), Sex=g.Select(u=>u.Element("sex").Value), Age=g.Select(u=>u.Element("age").Value), School=g.Select(u=>u.Element("university").Value), Phone=g.Select(u=>u.Element("phone").Value) }); foreach (var user in users) { ChartCount cc = new ChartCount(); cc.School = user.Num; cc.Count = user.Key; listcount.Add(cc); } return CollectionHelper.ToDataTable(listcount, null); }