如何用C#中的Dictonary <string,List <String >>的内容填充列表视图

Tho*_*eld 2 c# listview dictionary winforms

我有一本字典

Dictionary<string, List<string>> SampleDict = new Dictionary<string, List<string>>();
Run Code Online (Sandbox Code Playgroud)

我需要用Dictionary的内容填充listView

例如,"SampleDict"包含

One    A
       B
       C

Two    D
       E
       F
Run Code Online (Sandbox Code Playgroud)

listView应该像是一样填充

 S.No           Item       SubItem

  1             One           A,B,C
  2             Two           D,E,F
Run Code Online (Sandbox Code Playgroud)

现在我正在为这个方法使用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);
}
Run Code Online (Sandbox Code Playgroud)

还有其他方法可以像数据绑定那样做吗?

提前致谢.

Han*_*son 5

我很确定ListView不支持绑定到a,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);
}
Run Code Online (Sandbox Code Playgroud)

这就是所有需要的.