如何使用linq to dataSet将dataTable转换为数组?

时间:2011-06-16 15:06:59

标签: linq dataset

我有以下sql表架构:

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

使用c#代码我把它变成了dataSet。 如何使用linq to dataSet构建一个看起来像

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

由于

2 个答案:

答案 0 :(得分: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()
                };

如果没有,请告诉我,我会编辑。

答案 1 :(得分: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