In C#, is it possible to get all values of a particular column from all rows of a DataSet with a simple instruction (no LINQ, no For cicle)?
Why No LINQ? For people coming here without the same restriction, here are three ways to do this, the bottom two both using LINQ.
C#
<!-- Language: lang-cs -->List<object> colValues = new List<object>();
//for loop
foreach (DataRow row in dt.Rows) {
colValues.Add(row["ColumnName"]);
}
//LINQ Query Syntax
colValues = (from DataRow row in dt.Rows select row["ColumnName"]).ToList();
//LINQ Method Syntax
colValues = dt.AsEnumerable().Select(r => r["ColumnName"]).ToList();
VB
<!-- Language: lang-vb -->Dim colValues As New List(Of Object)
'for loop
For Each row As DataRow In dt.Rows
colValues.Add(row("ColumnName"))
Next
'LINQ Query Syntax
colValues = (From row As DataRow In dt.Rows Select row("ColumnName")).ToList
'LINQ Method Syntax
colValues = dt.Rows.AsEnumerable.Select(Function(r) r("ColumnName")).ToList
To use the AsEnumerable
method on a DataTable
, you'll have to have a Reference to System.Data.DataSetExtensions which add the LINQ extension methods. Otherwise, you can just cast the Rows
property of the DataTable
as type DataRow
(you don't have to do this with the Query syntax because it automatically casts for you).