实体类
Code
public class OnlineUserModel
{
public OnlineUserModel()
{
//
// TODO: Add constructor logic here
//
}
public string Callednumber{get;set;}
public int Total{get;set;}
public List<ProvinceUser> Provinces { get; set; }
}
public class ProvinceUser
{
public string ProvinceName { get; set; }
public int ProvinceCount { get; set; }
public List<CityUser> Citys { get; set; }
}
public class CityUser
{
public string CityName { get; set; }
public int CityCount { get; set; }
}
查询
Code
DataTable dt = getData(TextBox1.Text.ToString());
IEnumerable<DataRow> rows = dt.Rows.OfType<DataRow>();
var result = from row in rows
group row by row[3] into callnumber
select new OnlineUserModel
{
Callednumber = callnumber.Key.ToString(),
Total = callnumber.Sum(p => Convert.ToInt32(p[2])),
Provinces = (
from pr in rows.Where(x=>x[3]==callnumber.Key)
group pr by pr[0] into province
select new ProvinceUser
{
ProvinceName = province.Key.ToString(),
ProvinceCount = province.Sum(m => Convert.ToInt32(m[2])),
Citys =
(
from pw in rows.Where(y=>y[0]==province.Key)
group pw by pw[1] into citys
select new CityUser
{
CityName=citys.Key.ToString(),
CityCount=citys.Sum(n=>Convert.ToInt32(n[2]))
}
).ToList()
}
).ToList()
};
Code
{"Callednumber":"12590899766","Provinces":[{"Citys":[{"CityCount":5,"CityName":"北京"}],"ProvinceCount":5,"ProvinceName":"北京"},{"Citys":[{"CityCount":2,"CityName":"唐山"}],"ProvinceCount":6,"ProvinceName":"河北"}],"Total":11}
本意是先遍历省再遍历市,谁知在只遍历一个省中的一个市,初步怀疑与tolist有关。但生成实体 类必须这么做。