Darjeeling
Darjeeling

Reputation: 999

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

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

Upvotes: 6

Views: 15443

Answers (3)

Tim Schmelter
Tim Schmelter

Reputation: 460208

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")

Upvotes: 16

Soner G&#246;n&#252;l
Soner G&#246;n&#252;l

Reputation: 98810

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.

Upvotes: 2

Vishal Suthar
Vishal Suthar

Reputation: 17194

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

Upvotes: 1

Related Questions