Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One columned datatable to List<string>

Tags:

c#

linq

I have a datatable which contains only one column and all items are strings. How can I convert this to a List<string> using LINQ for example?

I Tried:

DataRow[] rows = dtusers.Select(); var qq = from RowCollection in rows          select new { UserCode = LibStatic.ToStr(RowCollection["UserCode"]) };  List<string> users = new List<string>(); users = qq.Cast<string>().ToList(); 

There is the easyway which always works:

foreach (DataRow dr in dtusers.Rows) {     users.Add(dr[0].ToString()); } 
like image 618
Sin5k4 Avatar asked Feb 28 '13 07:02

Sin5k4


People also ask

Can we convert DataTable to list?

There are the following 3 ways to convert a DataTable to a List. Using a Loop. Using LINQ. Using a Generic Method.

How do I convert a DataTable column to a comma separated string?

Select(s => s. Field<string>("Name")). ToArray(); string commaSeperatedValues = string. Join(",", SelectedValues);


2 Answers

You can use LINQ query to do that.

List<string> list = dtusers.AsEnumerable()                            .Select(r=> r.Field<string>("UserCode"))                            .ToList(); 
like image 117
Habib Avatar answered Sep 30 '22 19:09

Habib


You can try this code,

List<string> list = dt.Rows.OfType<DataRow>().Select(dr => (string)dr["ColumnName"]).ToList(); 
like image 32
Nitika Chopra Avatar answered Sep 30 '22 17:09

Nitika Chopra