37

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());
}
Bojan B
  • 2,091
  • 4
  • 18
  • 26
Sin5k4
  • 1,556
  • 7
  • 33
  • 57

2 Answers2

91

You can use LINQ query to do that.

List<string> list = dtusers.AsEnumerable()
                           .Select(r=> r.Field<string>("UserCode"))
                           .ToList();
Habib
  • 219,104
  • 29
  • 407
  • 436
5

You can try this code,

List<string> list = dt.Rows.OfType<DataRow>().Select(dr => (string)dr["ColumnName"]).ToList();
Nitika Chopra
  • 1,281
  • 17
  • 22