Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all values of a column from a DataSet

Tags:

c#

dataset

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)?

like image 256
Nelson Reis Avatar asked Nov 30 '22 12:11

Nelson Reis


1 Answers

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#

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

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).

like image 81
KyleMit Avatar answered Dec 13 '22 10:12

KyleMit