在列表视图中对项目进行分组

时间:2012-02-06 02:25:26

标签: c# winforms listview

我有一个声明的词典:

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

键是表示开关名称的字符串。该值是该交换机的端口对象列表。我试图使用以下代码将Dictionary中的项添加到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);

            }
        }

但是,我得到一个运行时错误,基本上说我在列表中有一个重复的项目。那讲得通。我试图通过dictinoary键(交换机名称)进行分组。有没有办法以某种方式对列表视图中的项目进行分组,或者动态地将Listviews添加到GroupBox中?基本上为Dictionary中的每个键添加一个新的ListView?我还在学习C#,表格仍然是新的。

1 个答案:

答案 0 :(得分:0)

您可以使用 LINQ查找按键选择器进行分组。 并且在添加到listview子项目时将portpair扩展为可枚举

这是我有时希望能帮到你的代码片段。

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;
 }