我有一个像
这样的对象public class Sales
{
public string Year { get; set; }
public string Item {get; set;}
public Dictionary<string,double> Sales { get; set; }
}
然后将其存储到Dictionary<string,double>
。
因此,假设我创建了两个Sales
个对象,例如:
obj 1 = {
Year = "2015",
Item = "Banana",
Sales = {
{"Week1", 2}
{"Week2", 24}
{"Week3", 69}
}
}
obj 2 = {
Year = "2015",
Item = "APPLE",
Sales = {
{"Week1", 3}
{"Week2", 4}
{"Week3", 8}
}
}
如何编写将结果返回到datagrid的linq查询,以便它具有以下行输出
第1行:年份,类别,第1周,第2周,第3周
第2行:2015年,Banana,2,24,69
第3行:2015年,Apple,3,4,8
答案 0 :(得分:0)
我会将所有内容放入DataTable中,然后将数据表作为控件的数据源。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Data;
namespace ConsoleApplication45
{
class Program
{
static void Main(string[] args)
{
List<Sales> sales = new List<Sales>() {
new Sales() {
year = 2015, item = "Banana", sales = new Dictionary<string,double>() {
{"Week1", 2}, {"Week2", 24},{"Week3", 69}
}
},
new Sales() {
year = 2015, item = "Apple", sales = new Dictionary<string,double>() {
{"Week1", 3}, {"Week2", 4},{"Week3", 8}
}
}
};
DataTable dt = new DataTable();
dt.Columns.Add("Year", typeof(int));
dt.Columns.Add("Category", typeof(string));
dt.Columns.Add("Week1", typeof(double));
dt.Columns.Add("Week2", typeof(double));
dt.Columns.Add("Week3", typeof(double));
foreach(Sales sale in sales)
{
dt.Rows.Add(new object[] {
sale.year,
sale.item,
sale.sales["Week1"],
sale.sales["Week2"],
sale.sales["Week3"]
});
}
}
}
public class Sales
{
public int year { get; set; }
public string item { get; set; }
public Dictionary<string, double> sales { get; set; }
}
}