2010-11-11 69 views
0

我通過從數據庫創建列表動態填充winforms組合框。檢查項目是否在組合框列表中

List<string> locationList = new List<string>(); 

     foreach(Data.DataSet.vwGet_RepListRow row in Data.Manager.TAM.RepListViewTableAdapter.GetData()) 
      locationList.Add(row.Location_City); 

     this.LocationComboBox.DataSource = locationList; 

我遇到的問題是,有現在一共有3個位置,但65名員工因此正在發生的事情是我得到在組合框中反覆城市。我如何編輯上面的內容來檢查新的Location_City是否已經不在locationList中?如果它不在那裏,然後添加它,但如果它在那裏,則跳過它。

任何幫助將是偉大的。

回答

2
if (!locationList.Contains(row.Location_City)) 
    locationList.Add(row.Location_City); 

locationList是類型列表,它實現IList的。因此,您可以使用Contains方法來檢查項目是否已經存在。

http://msdn.microsoft.com/en-us/library/system.collections.ilist.aspx

此外,你也可以使用一個HashSet,而不是列表,並使用其獨特的()方法。

http://msdn.microsoft.com/en-us/library/bb359438.aspx

+0

您還可以使用HashSet的;看我的編輯。 – 2010-11-11 14:46:34

1

更改您的代碼以包括以下檢查:

List<string> locationList = new List<string>(); 

     foreach(Data.DataSet.vwGet_RepListRow row in Data.Manager.TAM.RepListViewTableAdapter.GetData()) 
      string locationCity = row.Location_City; 
      if (!locationList.Contains(locationCity)) 
      { 
       locationList.Add(locationCity); 
      } 

     this.LocationComboBox.DataSource = locationList; 

首先,獲取表示要在本次迭代循環的增加城市的名稱的字符串。然後,檢查List中是否已經存在該值。如果不是,那麼你加上它;否則,你什麼都不做。

1

如果您使用的是.NET 3或更高它是非常容易使用LINQ:

this.LocationComboBox.DataSource = 
    Data.Manager.TAM.RepListViewTableAdapter.GetData(). 
    Select(r => r.Location_City).Distinct().ToArray(); 
相關問題