Elad Benda
Elad Benda

Reputation: 36656

how do I use linq to dataSet to convert dataTable to an array?

I have the following sql table schema:

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

Using c# code I got this into dataSet. How can I use linq to dataSet to build an array that looks like

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

Thanks

Upvotes: 1

Views: 2489

Answers (2)

Justin Morgan
Justin Morgan

Reputation: 30715

I think this will work:

    //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()
                };

If that doesn't do it, let me know and I'll edit.

Upvotes: 1

Elad Benda
Elad Benda

Reputation: 36656

I think I'll do this in two steps:

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

Upvotes: 0

Related Questions