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)?
问题:
回答1:
Only by iterating over the rows, as Utaal noted in this answer.
You might expect that the DataTable.DefaultView.RowFilter
would support grouping, but it does not (it mainly offers the equivalent functionality of a Where
clause, with some basic aggregations - though not simple grouping).
回答2:
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).
回答3:
As far as I know there's no direct way to get those; but the for-loop is pretty straightforward and obviously won't be more resource-intensive than anything else.
回答4:
In addition to Utaal's answer, you can possibly populate a new DataTable object with the results of a query that selects only one column from your original data source, assuming it's an RDBMS. This has the advantage of letting you specify things that are easy to express in code but easy to express in SQL like DISTINCT
queries.