对象中的Linq Flatten字典
本文关键字:Flatten 字典 Linq 对象 | 更新日期: 2023-09-27 18:10:41
我有一个对象,如
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}
}
}
如何编写linq查询,将结果返回到datagrid,使其具有以下行输出
第1行:年份、类别、周1、周2、周3
第二行:2015,香蕉,2,24,69
第3行:2015,Apple, 3,4,8
我将把所有内容放入一个DataTable中,然后使该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; }
}
}