How to convert a column of DataTable to a List
Try this:
static void Main(string[] args)
{
var dt = new DataTable
{
Columns = { { "Lastname",typeof(string) }, { "Firstname",typeof(string) } }
};
dt.Rows.Add("Lennon", "John");
dt.Rows.Add("McCartney", "Paul");
dt.Rows.Add("Harrison", "George");
dt.Rows.Add("Starr", "Ringo");
List<string> s = dt.AsEnumerable().Select(x => x[0].ToString()).ToList();
foreach(string e in s)
Console.WriteLine(e);
Console.ReadLine();
}
var list = dataTable.Rows.OfType<DataRow>()
.Select(dr => dr.Field<string>(columnName)).ToList();
[Edit: Add a reference to System.Data.DataSetExtensions
to your project if this does not compile]
Here you go.
DataTable defaultDataTable = defaultDataSet.Tables[0];
var list = (from x in defaultDataTable.AsEnumerable()
where x.Field<string>("column1") == something
select x.Field<string>("column2")).ToList();
If you need the first column
var list = (from x in defaultDataTable.AsEnumerable()
where x.Field<string>(1) == something
select x.Field<string>(1)).ToList();
Is this what you need?
DataTable myDataTable = new DataTable();
List<int> myList = new List<int>();
foreach (DataRow row in myDataTable.Rows)
{
myList.Add((int)row[0]);
}
I do just like below, after you set your column AsEnumarable you can sort, order or how you want.
_dataTable.AsEnumerable().Select(p => p.Field<string>("ColumnName")).ToList();