views:

7038

answers:

6

How to select distinct values from datatable in C#?

For a retrieved data from database, I need to get its distinct value in C#?

+1  A: 

in C#? you should use SELECT DISTINCT(field) in your SQL

TheSimon
I need to select distinct values from grouped sql statement.
Ahmed
+2  A: 

If by "in C#" you mean using LINQ then you can use the Distinct Operator.

Dan Diplo
A: 

sthing like ?

SELECT DISTINCT .... FROM table WHERE condition

http://www.felixgers.de/teaching/sql/sql_distinct.html

note: Homework question ? and god bless google..

http://www.google.com/search?hl=en&rlz=1C1GGLS_enJO330JO333&q=c%23+selecting+distinct+values+from+table&aq=f&oq=&aqi=

Madi D.
to whomever downvoted me :S,, obviously the question was modified after my answer ?? (answer 10:15, question edited on 12:15 ) oh well.. thx for ur ignorance :)
Madi D.
+5  A: 
DataTable dt = new DataTable();
dt.Columns.Add("IntValue", typeof(int));
dt.Columns.Add("StringValue", typeof(string));
dt.Rows.Add(1, "1");
dt.Rows.Add(1, "1");
dt.Rows.Add(1, "1");
dt.Rows.Add(2, "2");
dt.Rows.Add(2, "2");

var x = (from r in dt.AsEnumerable()
        select r["IntValue"]).Distinct().ToList();
Martin Moser
+8  A: 
DataView view = new DataView(table);
DataTable distinctValues = view.ToTable(true, "Column1", "Column2" ...);
Thomas Levesque
A: 

To improve the above answer: The ToTable function on dataview has a "distinct" flag.

//This will filter all records to be distinct
dt = dt.DefaultView.ToTable(true);
Ravedave
This doesn't appear to work. There is only one overload with a distinct Boolean parameter in it and it requires the parameter array. I think this will just return a table called "True" without any DISTINCT applied.
proudgeekdad