Multi level dictionary error in c#

221 views Asked by At

Im using the following code to make JSON

        FilterModel f = new FilterModel();
        f.FilterName = "EducationLevel";
        f.filterValue = new List<string>();
        f.filterValue.Add("BE");
        f.GroupName="Education";


        FilterDictionary d = new FilterDictionary();
        d.FilterValuse = new Dictionary<string, List<string>>();
        d.FilterValuse.Add(f.FilterName, f.filterValue);

        FilterSelectModel ff = new FilterSelectModel();

        ff.Filters = new Dictionary<string, Dictionary<string, List<string>>>();

        ff.Filters[f.GroupName].Add(f.FilterName, f.filterValue);



        var json = new JavaScriptSerializer().Serialize(ff);
        Response.Write(json);

but it shows an exception in the bellow line

ff.Filters[f.GroupName].Add(f.FilterName, f.filterValue);

it shows the following error

The given key was not present in the dictionary

What went wrong ? any one can help me

1

There are 1 answers

0
Arun Chandran Chackachattil On BEST ANSWER

Change this code:

ff.Filters[f.GroupName].Add(f.FilterName, f.filterValue);

To:

ff.Filters.Add(f.GroupName, new Dictionary<string, List<string>>() 
 { {f.FilterName, f.filterValue} });

Hope this will resolve your issue.

Check out this How to: Initialize a Dictionary with a Collection Initializer (C# Programming Guide)