我使用存儲過程來獲得結果,然後我有一個填充結果的數據表。從那裏結果填充到ListBox中。我得到重複的ID,我想刪除重複的結果。隱藏ListBox中的重複結果?
private DataTable _dt = new DataTable();
ListBox1.DataSource = _dt;
ListBox1.DataValueField = "userId"; //column name in DT
ListBox1.DataBind();
我使用存儲過程來獲得結果,然後我有一個填充結果的數據表。從那裏結果填充到ListBox中。我得到重複的ID,我想刪除重複的結果。隱藏ListBox中的重複結果?
private DataTable _dt = new DataTable();
ListBox1.DataSource = _dt;
ListBox1.DataValueField = "userId"; //column name in DT
ListBox1.DataBind();
我認爲喬爾的答案會在你的情況下工作。但是,我可能會嘗試避免首先返回重複項,在存儲過程中使用DISTINCT
。這樣,如果您或其他人再次需要相同的數據,則無需到處過濾出重複的數據。另外,您還可以從數據庫和Web服務器之間通過網絡發送不必要的數據獲得第二個好處。
如果您使用LINQ可以使用:
var source = _dt.Distinct();
ListBox1.DataSource = source;
ListBox1.DataValueField = "userId";
ListBox1.DataBind();
編輯: 好吧,在研究一個更貼切一點,我發現System.Data.DataRowCollection
不落實了IEnumerable擴展方法與典型的IEnumerable相同的方式,如List
。爲了使用Distinct()
擴展方法,您首先需要將行集設置爲更基本的IEnumerable。
IEnumerable<System.Data.DataRow> rows = (IEnumerable<System.Data.DataRow>)_dt.Rows;
ListBox1.DataSource = rows.Distinct();
ListBox1.DataValueField = "userId";
ListBox1.DataBind();
雖然它的工作原理可能並不像@Massimiliano提供的答案那麼簡單也沒有效率。
DataTable distinctTable = originalTable.DefaultView.ToTable(/*distinct*/ true);
ListBox1.DataSource = distinctTable ;
ListBox1.DataValueField = "userId";
ListBox1.DataBind();
O啊,我忘了關於獨特的,謝謝 – nhat