archytect
archytect

Reputation: 3715

How to initialize a dictionary in class object in mvc

I want to create a Request model that's dynamic where I can add my own custom fields. Just read a lot about generics and was wondering if something like this was possible.

 public class Request
 {
      public string Action { get; set; }
      public List<DynamicQueries> Queries { get; set; }
 }

 public class DynamicQueries {
      public Dictionary<string,string> Query { get; set; }
 }

in order to do something like

 var ReqObj = new Request() {
 Action = "GetUsers",
 Queries = new List<DynamicQueries> {
      new DynamicQueries {
           Query = new Dictionary<string,string> {
                { "Query1", "True" },
                { "Query2", "false" }
           }
      }
 }

It prints out

 {
 "Action": "GetUsers",
      "Queries": [
      {
           "Query": {
                "Query1": "True",
                "Query2": "false"
           }
       }
       ]
 }

How do I get it to output this instead?

 {
      "Action": "GetUsers",
      "Query1": "True",
      "Query2": "false"
 }

Upvotes: 0

Views: 771

Answers (1)

Maarten
Maarten

Reputation: 22945

You need to add the instantiation of the DynamicQueries instance, and use more { and } to initialize the dictionary.

var ReqObj = new Request() {
    Action = "GetUsers",
    Queries = new List<DynamicQueries> {
        new DynamicQueries {
            Query = new Dictionary<string,string> {
                { "Query1", "True" },
                { "Query2", "false" }
            }
        }
    }
};

Note: Your question title really doesn't describe what you are asking. I think you should change it to 'How to add an initializer to a dictionary' or something.

Upvotes: 1

Related Questions