Tag: DataSet
Select Distinct on DataSets
by admin on Aug.04, 2010, under tech
Have you ever wondered how to do a “SELECT DISTINCT” on a dataset column? Well, here’s the low down:
I came across this handy little method for querying a DataSet for distinct records . Say that my data is already in my app and I need to do something with it. Going back to SQL or re-writing the query just isn’t an option, so what can I do?
Microsoft has a helpful kb where it defines a dataset helper class and a SelectDistinct method for accessing data in this way – here. But as always, Microsoft makes simple things complicated. And who wants to write a bunch of classes and functions when we can do the same thing in one line?
Say we have a DataSet ds like so:
| ID | grID | value |
| 1 | 100 | abc |
| 2 | 100 | def |
| 3 | 110 | efg |
| 4 | 120 | hij |
To select distinct grIDs we can just do this:
DataTable distinctDT = ds.Tables[0].DefaultView.ToTable(true, new string [] { “grID” });
This returns:
| grID |
| 100 |
| 110 |
| 120 |
We can now use this distinct DataTable to make our queries on our original DataSet:
ds.Tables[0].Select(“grID = ” distinctDT.Rows[0]["grID"].toString());
Yeah! No helper classes and no extra methods taking up that valuable development space. Hope this helps someone!