我使用存储过程来获得结果,然后我有一个填充结果的数据表。从那里结果填充到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