Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert dataset to list<double> and list<string> C#

Tags:

c#

list

dataset

my data looks like this:

+=======+========+
| year  |sales   |
+=======+========+
| 2008  |100000  |
| 2009  |120040  |
| 2010  |239000  |
| 2011  |300900  |
| 2012  |200900  |
+=======+========+

can I convert a dataset to list of double and string? the first column of the dataset will be list<string> and the second column is list<double>

is there any solution? thanks

like image 461
Darjeeling Avatar asked Jan 04 '13 08:01

Darjeeling


3 Answers

I wonder why a year is a string, however...

List<string> years   = dataSet.Tables[0].AsEnumerable()
                            .Select(r => r.Field<string>(0))
                            .ToList();
List<double> doubles = dataSet.Tables[0].AsEnumerable()
                            .Select(r => r.Field<double>(1))
                            .ToList();

Note that you need to add using System.Linq;.

You can use the Field extension method with the column's ordinal in the DataRow or via it's name: r.Field<string>("year")

like image 66
Tim Schmelter Avatar answered Sep 18 '22 10:09

Tim Schmelter


Try like this;

List<string> years   = dataSet.Tables[0].AsEnumerable()
                            .Select(n => n.Field<string>(0))
                            .ToList();

And (1) for sales column.

Don't remember to add System.Data.DataSetExtensions namespace. Also look at from MSDN DataTableExtensions.AsEnumerable() method.

Returns an IEnumerable object, where the generic parameter T is DataRow. This object can be used in a LINQ expression or method query.

like image 42
Soner Gönül Avatar answered Sep 21 '22 10:09

Soner Gönül


1)

var myyear = ds.Tables[0].AsEnumerable()
                         .Select(r => new {
                                 column1 = r.Field<string>("year")
                                 });

List<string> year = myyear.ToList();

2)

var mysales = ds.Tables[0].AsEnumerable()
                          .Select(r => new {
                                  column2 = r.Field<double>("sales")
                                 });

List<double> sales = mysales.ToList();
like image 23
Vishal Suthar Avatar answered Sep 20 '22 10:09

Vishal Suthar