How to convert a column of DataTable to a List
142,469
Solution 1
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();
}
Solution 2
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]
Solution 3
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();
Solution 4
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]);
}
Solution 5
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();
Related videos on Youtube
Author by
shrishjain
Updated on July 05, 2022Comments
-
shrishjain almost 2 years
I have a DataTable with multiple columns. I want to get a
List<String>
out of first column of DataTable. How can I do that? -
Wes Grant over 12 yearsAsEnumerable() works on a DataTable as well. var list = dataTable.AsEnumerable().Select(r => r.Field<string>(columnName)).ToList();
-
Brk over 10 yearsIf
DataTable.AsEnumerable()
does not compile, add a reference to System.Data.DataSetExtensions to your project. -
InteXX almost 10 yearsIs anyone else getting a ReadOnly error on Columns?
-
GorvGoyl over 8 yearshow to retrieve data from a column "name"?
-
chiapa almost 8 yearsWhat if you don't know the
columnName
? -
Cengiz Araz over 6 yearsI would choose AsEnumerable() method instead of this. This is like holding the right ear with left hand.
-
AaA over 6 yearsYour answer is almost correct except, question is asking for names or
List<String>
-
clamchoda over 4 years@JerryGoyal Late reply, but for anyone else wondering just replace
x[0]
withx["Lastname"]
. Lastname being the name of the column we're interested in. -
PastExpiry.com about 4 yearsmight want to mention that this 'simple' code requires .Net 4.5 or higher AND a nuget package which you have to install via "Install-Package System.Data.DataSetExtensions -Version 4.5.0"