简体   繁体   中英

Multi level dictionary error in c#

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM