How to get the Selected columns form the DataTable?
For e.g my BaseTable has three columns,
ColumnA,
ColumnB and
ColumnC.
Now as part of intermediate operations, I need to retrieve all the rows only from the ColumnA. Is there any predefined formula just like DataTable.Select?
Asked
Active
Viewed 1.8k times
5
-
What would be the purpose of pulling only one column? If you leave all three columns there, you can always take just the first column with `DataTable.Rows[i]["ColumnA"]` when you are looping through data. – mellamokb Sep 26 '11 at 22:58
-
1I need to set the distinct row values of Column-A into a listBox. – Krishna Sep 26 '11 at 23:02
-
I can create a DataView and eliminate the unnecessary columns from there. But its a two-step procedure and chokes if the datatable size is huge. – Krishna Sep 26 '11 at 23:03
-
DataView dv = dt.DefaultView; DataTable dtColA = dv.ToTable(true, new string[] { "Column-A" }); – Krishna Sep 26 '11 at 23:04
-
What .NET framework are you using? Is LINQ an option for you? – csm8118 Sep 26 '11 at 23:05
-
I need for FrameWork 2.0 – Krishna Sep 26 '11 at 23:06
-
@Murali: Can you add the distinct values part into your question? Otherwise your question doesn't make sense. Thanks :-) – mellamokb Sep 26 '11 at 23:09
2 Answers
7
DataView view = new DataView(MyDataTable);
DataTable distinctValues = view.ToTable(true, "ColumnA");
Now you can select.
DataRow[] myRows = distinctValues.Select();

CharithJ
- 46,289
- 20
- 116
- 131
-
I used the similar one which I already posted in the comments. It works fine for me. Just looking for any other better solution which doesn't effects the performance. Anyways I am OK with this for now. Thanks a lot. – Krishna Sep 26 '11 at 23:15
2
From this question: How to select distinct rows in a datatable and store into an array you can get the distinct values:
DataView view = new DataView(table);
DataTable distinctValues = view.ToTable(true, "ColumnA");
If you're dealing with a large DataTable and care about the performance, I would suggest something like the following in .NET 2.0. I'm assuming the type of the data you're displaying is a string so please change as necessary.
Dictionary<string,string> colA = new Dictionary<string,string>();
foreach (DataRow row in table.Rows) {
colA[(string)row["ColumnA"]] = "";
}
return colA.Keys;
-
Minimum number of rows will be around 50K and this should be implemented for all the 26 columns. So foreach, for and while loops are out of question. – Krishna Sep 26 '11 at 23:17
-
Anyways, the above solution works for me. I am sure your solution will be perfect for the small data objects. – Krishna Sep 26 '11 at 23:18