【问题标题】:How to fill a list view with the contents of Dictonary<string,List<String>> in C#如何在 C# 中用 Dictionary<string,List<String>> 的内容填充列表视图
【发布时间】:2011-03-06 17:55:23
【问题描述】:

我有一本字典

Dictionary<string, List<string>> SampleDict = new Dictionary<string, List<string>>();

我需要用 Dictionary 的内容填充 listView

例如“SampleDict”包含

One    A
       B
       C

Two    D
       E
       F

listView 应该像这样填充

 S.No           Item       SubItem

  1             One           A,B,C
  2             Two           D,E,F

现在我正在为这个方法使用 for 循环

喜欢

List<String> TepmList=new List<String>(SampleDict.Keys); 

for(int i=0;i<TepmList.Count;i++)
{
    listView1.Items.Add((i+1).ToString());
    listView1.Items[i].SubItems.Add(TepmList[i]);
    List<String>Lst=SampleDict[TepmList[i]])
    String Str="";
    int K=0;
    for(int j=0;j<Lst.Count;j++)
    {
        string s=Lst[j];
        k++;
        if(k==1)
            Str=s;
        else
            Str=","+Str;
    }
    listView1.Items[i].SubItems.Add(Str);
}

有没有其他方法可以做到这一点,比如数据绑定?

提前致谢。

【问题讨论】:

  • 您想为您的 GUI 使用哪种技术? WPF、WinForm...

标签: c# winforms listview dictionary


【解决方案1】:

我很确定 ListView 不支持绑定到 Dictionary 但您可以大大简化代码:

foreach(KeyValuePair<string, List<string>> kvp in SampleDict)
{
     ListViewItem lvi = listView1.Items.Add(kvp.Key);
     string temp = string.Join(", ", kvp.Value);
     lvi.SubItems.Add(temp);
}

这就是我们所需要的。

【讨论】:

    【解决方案2】:

    您可以为字典中的值项实现自己的集合,并覆盖 ToString() 方法以提供以逗号分隔的项列表。

    class StringList : List<string> {
       public override string ToString() {
          string result = string.Empty;
          foreach( string item in this ) {
             if( result.Length != 0 ) {
                result += ",";
             }
             result += item;
          }
          return result;
       }
    }
    

    本质上,您只是将相同的代码移到更好的地方,但这样可以更好地重用。你的字典会变成:

    Dictionary<string, StringList> SampleDict = new Dictionary<string, StringList>();
    

    在此之后,您上面的代码会简化很多。

    【讨论】:

    • 您可以使用 using 关键字来执行相同操作,而无需定义自己的类,即定义您在运行时键入:using List&lt;String&gt; = StringList;。您的循环也等于String.Join 方法。
    【解决方案3】:
            int Index=0;
            foreach(KeyValuePair<String,List<String>>KVP in Dict)
            {
                ListViewItem LVI = listView1.Items.Add((Index + 1).ToString());
                LVI.SubItems.Add(KVP.Key);
                LVI.SubItems.Add(KVP.Value.Select(X => X).Aggregate((X1, X2) => X1 + "," + X2));
                Index++;
    
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-16
      • 2011-07-09
      • 2020-10-28
      • 1970-01-01
      • 1970-01-01
      • 2012-12-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多