2012-02-06 77 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; 
}