views:

88

answers:

3

I've a Dictionary

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

I need to fill a listView with the contents of the Dictionary

For example the "SampleDict" contains

One    A
       B
       C

Two    D
       E
       F

The listView should be filled like

 S.No           Item       SubItem

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

Now i'm using for loop for this method

like

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

is there any other way to do this like data binding ?

Thanks in advance.

+4  A: 

I'm fairly sure ListView don't support binding to a Dictionary but you could simplify your code a lot:

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

Is all that's needed.

ho1
+1  A: 

You could implement your own collection for the value items in your dictionary, and override the ToString() method to provide the comma-delimited list of items.

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

Essentially you're just moving the same code to a better place, but it would allow for better reuse. Your dictionary will become:

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

After this your code above would simplify a lot.

PjL
you can do the same using `using` keyword without defining own class, i.e. define you type on-the-fly: `using List<String> = StringList;`. Also your loop is equal to `String.Join` method.
abatishchev
But use a StringBuilder
MaLio
A: 
        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++;

        }
Pramodh