Linq Flatten 对象中的字典

Linq Flatten Dictionary in object

我有一个对象

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 查询来 return 数据网格的结果,以便它具有以下行输出

第 1 行:年、类别、第 1 周、第 2 周、第 3 周

第 2 行:2015 年,香蕉,2、24、69

第 3 行:2015 年,Apple,3、4、8

我会把所有东西都放到一个数据表中,然后让数据表成为控件的数据源。

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; }
    } 
}