2015-08-31 89 views
0

我有諸如LINQ的平鋪在字典對象

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查詢,將結果返回到數據網格,以便它有以下行輸出

行1:年,類別,Week1,Week2,譯員更加

行2:2015,香蕉,2,24,69

行3:2015年,蘋果,3,4,8

回答

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

不是我一直在尋找的,但我得到它的工作使用您的代碼,所以謝謝! – Chadbur