-5

Here is the sample i need to form. I tried hash set it is showing as key and value but i need my output to be in the below format.

[{
    "data": "Name"

},
{
    "data": "Description"
}]

My sample code:

var items = new List<KeyValuePair<string, string>>();

foreach (DataColumn col in dt.Columns)
        {
            if (col.ColumnName !="DataType")
            {
                items.Add(new KeyValuePair<string, string>("data", 
col.ColumnName));
            }
        }
var lookup = items.ToLookup(kvp => kvp.Key, kvp => kvp.Value);

When i try to add dictionary it throws me error saying key has already been added. Any guide to learn dictionary concepts in c#

Thanks

Eliotjse
  • 123
  • 14

2 Answers2

3

The given json is an array of objects and can be created with

var source = new List<object>{
    new Dictionary<string,object>{ { "data", "Name" }, },
    new Dictionary<string,object>{ { "data", "Description" }, },
};

var json = JsonConvert.SerializeObject( source, Formatting.Indented );

.NET fiddle Sample

Sir Rufo
  • 16,671
  • 2
  • 33
  • 66
0

You cannot add two key-value pairs to the same dictionary. The dictionary uses the key to calculate a hash. If you add two keys that are the same, you'll get a collision of the hashes. This will prevent the dictionary from working properly - when you try to get an item with that key, which item should the dictionary return?

Dido
  • 501
  • 2
  • 6
  • 19