110,571
社区成员
发帖
与我相关
我的任务
分享
List<string[]> list = new List<string[]>();
list.Add(new string[] { "中国", "北京", "100W人" });
list.Add(new string[] { "中国", "上海", "200W人" });
list.Add(new string[] { "中国", "南京", "300W人" });
list.Add(new string[] { "日本", "东京", "2人" });
list.Add(new string[] { "美国", "洛杉矶", "150W人" });
list.Add(new string[] { "日本", "大阪", "1人" });
list.Add(new string[] { "美国", "旧金山", "80W人" });
var query = list.GroupBy(p => p[0]).Select(p => p);
StringBuilder sb = new StringBuilder();
foreach(var p in query)
{
string str = p.First()[0] + ":";
foreach(string[] c in p)
{
str += "(" + c[1] + " " + c[2] + ")";
}
sb.AppendLine(str);
}
Console.WriteLine(sb.ToString());
输出:
中国:(北京 100W人)(上海 200W人)(南京 300W人)
日本:(东京 2人)(大阪 1人)
美国:(洛杉矶 150W人)(旧金山 80W人)public static DataTable GetPivot(List<ReportType> records)
{
var result = new DataTable();
result.Columns.Add("国家", typeof(string)); //定义第一列
var columnNames = records.GroupBy(x => x.City).Select(g => g.Key).ToList();
columnNames.ForEach(name => result.Columns.Add(name, typeof(string))); //其它列
records.ForEach(r =>
{
var dr = result.Rows
.Cast<DataRow>()
.Where(x => (string)x["国家"] == r.Country)
.FirstOrDefault();
if (dr == null)
{
dr = result.NewRow(); //创建新记录
dr["国家"] = r.Country; //第一列的值
result.Rows.Add(dr);
}
dr[r.City] = r.Value; //城市列对应的值
});
return result;
}
这次我拿机器编译了一下,可以编译通过。public static DataTable GetPivot(List<ReportType> records)
{
var result = new DataTable();
result.Columns.Add("国家", typeof(string)); //定义第一列
var columnNames = records.GroupBy(x => x.City).Select(g => g.Key).ToList();
columnNames.ForEach(name => result.Columns.Add(name, typeof(string))); //其它列
records.ForEach(r =>
{
var dr = result.Rows
.Cast<DataRow>()
.Where(x => (string)x["国家"] == r.Country)
.FirstOrDefault();
if (dr == null)
{
var dr = result.NewRow(); //创建新记录
dr["国家"] = r.Country; //第一列的值
dr[r.City] = r.Value; //城市列对应的值
result.Rows.Add(dr);
}
else
dr[r.City] = r.Value; //城市列对应的值
});
return result;
}
List<ReportType> result;
using (var conn = SqlHelper.OpenConnection())
{
var cmd = SqlHelper.GetCommand(conn, "select * from [table] where [报告年份]=@year");
SqlHelper.SetParameter(cmd, "year", 2015);
result = (from IDataRecord rd in cmd.ExecuteReader()
select new ReportType
{
Countty = (string)rd["字段1"],
City = (string)rd["字段2"],
Value = (string)rd["字段3"],
}).ToList();
}
这里的变量result返回你列出的数据集合。
那么,转换为一个DataTable就很容易,可以这样:public static DataTable GetPivot(List<ReportType> records)
{
var result = new DataTable();
result.Columns.Add("国家",typeof(string)); //定义第一列
var columnNames = records.GroupBy(x => x.City).Select(g => g.Key).ToList();
columnNames.ForEach(name => result.Columns.Add(name, typeof(string))); //其它列
records.ForEach(r =>
{
var dr = result.NewRow(); //创建新记录
dr["国家"] = r.Country; //第一列的值
dr[r.City] = r.Value; //城市列对应的值
result.Rows.Add(dr);
});
return result;
}
最后这个转换函数 GetPivot 的设计逻辑其实非常通用,基本上这类转换全都大同小异。你甚至可以把这里的 Contry、City 字段/属性名重新命名为 X_Title、Y_Title 从而可以把这个GetPivot 方法用于通用的目的。