Reputation: 1169
I use a Store Procedure to get the results and then I have a Datatable that fill in the results. From there the results are filled in a ListBox. I'm getting duplicate IDs and I want to remove the duplicate results.
private DataTable _dt = new DataTable();
ListBox1.DataSource = _dt;
ListBox1.DataValueField = "userId"; //column name in DT
ListBox1.DataBind();
Upvotes: 0
Views: 178
Reputation: 37543
If you use linq you can use:
var source = _dt.Distinct();
ListBox1.DataSource = source;
ListBox1.DataValueField = "userId";
ListBox1.DataBind();
Edit:
Ok, in researching a little more closely I've found that the System.Data.DataRowCollection
does not implement the IEnumerable extension methods in the same manner as a typical IEnumerable such as List
. In order to use the Distinct()
extension method, you would need first to get the row set into a more basic IEnumerable.
IEnumerable<System.Data.DataRow> rows = (IEnumerable<System.Data.DataRow>)_dt.Rows;
ListBox1.DataSource = rows.Distinct();
ListBox1.DataValueField = "userId";
ListBox1.DataBind();
While it works, it probably is not nearly as simple nor as efficient as the answer supplied by @Massimiliano.
Upvotes: 2
Reputation: 11406
I think Joel's answer would work in your case. However, I'd probably try to avoid returning duplicates in the first place, by using DISTINCT
in the stored procedure. This way, if you or somebody else needs the same data again, they don't have to filter out duplicates everywhere. Plus, you get the secondary benefit of not sending unnecessary data over the network between your database and web servers.
Upvotes: 1
Reputation: 26737
DataTable distinctTable = originalTable.DefaultView.ToTable( /*distinct*/ true);
ListBox1.DataSource = distinctTable ;
ListBox1.DataValueField = "userId";
ListBox1.DataBind();
http://msdn.microsoft.com/en-us/library/wec2b2e6.aspx
Upvotes: 2