2012-02-06 76 views
0

我有一個正是如此聲明的解釋:分組列表中的項目視圖

Dictionary myDictionary<string, List<FCPort>> = new Dictionary<string, List<FCPort>>(); 

關鍵是表示開關名稱的字符串。該值是該交換機的端口對象列表。我想在詞典中的項目與此代碼添加到ListView:

foreach (KeyValuePair<string, List<FCPort>> portpair in results) 
     {    
      ListViewItem item1 = new ListViewItem(portpair.Key); 
      foreach (FCPort port in portpair.Value) 
      { 
       item1.SubItems.Add(port.FCIDList[0]); 
       item1.SubItems.Add(port.WWPNList[0]); 
       item1.SubItems.Add(port.TextSerializePortName()); 
       this.ResultsListView.Items.Add(item1); 

      } 
     } 

不過,我得到一個運行時錯誤基本上是說,我在列表中的重複項目。這就說得通了。我試圖按照字母鍵(開關名稱)進行分組。有沒有辦法以某種方式將列表視圖中的項目分組,或動態地將Listviews添加到GroupBox中?基本上爲Dictionary中的每個鍵添加一個新的ListView?我仍然在學習C#,表單仍然是新的。

回答

0

您可以使用LINQ查找按您的密鑰選擇器進行分組。 並擴展你的portpair到enumerable時添加到列表視圖子項

這是我有時希望可以幫助你的代碼片段。

Dictionary<String, Country> dict = new Dictionary<string, Country>(); 
dict.Add("Toronto", Country.Canada); 
dict.Add("New York", Country.US); 
dict.Add("Vancover", Country.Canada); 
dict.Add("Seattle", Country.US); 
dict.Add("Fredericton", Country.Canada); 

Lookup<Country,String> lookup = (Lookup<Country,String>) dict.ToLookup(pair =>pair.Value, pair => pair.Key); 

foreach (var countryGroup in lookup) 
{ 
    item = new ListViewItem(countryGroup.Key.ToString()); 
    item.SubItems.Add(string.Format("{0}", string.Join(",", countryGroup.Select(s => "@" + s)))); 
    lv.Items.Add(item); 
    item = null; 
}