2012-02-14 74 views
4

如何檢查值是否已存在於列表框中,以便我可以避免重複?如何在asp.net中添加之前檢查列表框中是否已經存在一個值

我已經向服務器端列表框添加了一些值,當我添加到列表中時,我得到了更多的重複項。

如何避免重複?

lst_Viewers.Items.Add(reader["Name"].ToString()); 
+0

添加之前可能清除列表框嗎?那麼你永遠不會得到重複或過時的項目。 – abatishchev 2012-02-14 10:51:32

+0

@abatishchev這不是Murthy想要的。他希望在檢查重複值之前將項目添加到列表框中。 – Sukanya 2012-02-14 12:17:46

回答

1
if(!lst_Viewers.Items.Any(item => item.Value.ToString().Equals(reader["Name"].ToString()) 
    lst_Viewers.Items.Add(reader["Name"].ToString()); 
7
ListItem item = new ListItem(reader["Name"].ToString()); 
if (! lst_Viewers.Items.Contains(item)){ 
    lst_Viewers.Items.Add(item); 
} 

var name = reader["Name"].ToString(); 
ListItem item = lst_Viewers.Items.FindByText(name); 
if (item == null){ 
    lst_Viewers.Items.Add(new ListItem(name)); 
} 
1

另一種方法可以是所有的值插入到List<string>那麼只有在循環後添加的項目,使用.Distinct()獲得唯一的值:

List<string> names = new List<string>(); 
while (reader.Read()) 
    names.Add(reader["Name"].ToString()) 
names.Distinct().ToList().ForEach(name => lst_Viewers.Items.Add(name)); 

這樣,您不必在每次迭代中搜索整個DropDown - 更優雅(在我看來)並且更高效。

相關問題