2011-06-16 86 views
1

我有以下SQL表模式:如何使用linq to dataSet將dataTable轉換爲數組?

procudtId productPrice Color 
================================== 
1   3 $   Blue 
1   3 $   Red 
1   3 $   Green 
2   5 $   Blue 
2   5 $   Red 

使用C#代碼,我得到這個到數據集。 我如何使用LINQ到數據集建立一個數組,看起來像

[ price:"3$", ColorList:<"Blue","Red","Green"> ; 
    price:"5$", ColorList:<"Blue","Red">] 

感謝

回答

1

我認爲這會工作:

//dt is the DataTable you're working with. 
    var groups = from row in dt.AsEnumerable() 
       group row["Color"] by row["productPrice"] into prices 
       select prices; 

    var query = from g in groups 
       select new 
       { 
        price = g.Key, 
        ColorList = g.ToList() 
       }; 

如果這樣做不了,讓我知道,我會編輯。

+0

我會檢查。謝謝。順便說一句linq翻譯到「group by + having」是什麼?是否就像你上面寫的方式:按行[「productPrice」]將組行[「Color」]轉換爲價格? – 2011-06-16 15:50:28

+0

希望有所幫助。基本上,它按行[「productPrice」]對所有行[「Color」]值進行分組,因此每個價格都成爲一個組,並且該價格的每種顏色都放在該組中。 [這是關於LINQ的組子句的更多信息](http://msdn.microsoft.com/en-us/library/bb384063.aspx)。 – 2011-06-16 15:59:02

0

我想我會在兩個步驟做到這一點:

1. create the color lists 
    var dataRows = from row in ds.Tables[0].AsEnumerable() 
        //group row by row.Field<Int32>("TierId") 
        where row.Field<Int32>("ProductId") == 1 
        select 
         row.Field<String>("Color"); 

    List<String> list = dataRows.ToList(); 

2. acquire the product price 
3. combine them both to array 
+1

這是3個步驟。 :P – 2011-06-16 15:40:42