0

I am using Zip to combine two list with same count.

List<NameDTO> _nameDetials = new List<NameDTO>();
List<ValDTO> _valDetials = new List<ValDTO>();
var combined = _nameDetials
    .Zip(_valDetials, (name, val) => new KeyValuePair<NameDTO, ValDTO>(name, val));

I get results for _nameDetails and _valDetails as senter image description herehown in below images 3 and 4 enter image description here

Used below code to convert to json

var jsonSerialiser = new JavaScriptSerializer();
var json = jsonSerialiser.Serialize(combined);

I am getting a result shown in image1 enter image description here

But I need a output as shown in image 2 enter image description here

Any help is kindly appreciated. Thanks

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
shyam
  • 37
  • 5
  • Possible duplicate of [JSON Serialize List>](https://stackoverflow.com/questions/21021655/json-serialize-listkeyvaluepairstring-object) – mjwills Jun 24 '17 at 12:48
  • https://stackoverflow.com/questions/41503024/serialize-listkeyvaluepairstring-string-as-json may be of use if you can use a Dictionary rather than just a sequence of KeyValuePair. – mjwills Jun 24 '17 at 12:51

1 Answers1

4

You can extend your Zip call with an ToDictionary call like so.

var combined = _nameDetials
    .Zip(_valDetials, (name, val) => new  { name.Name, val.Val })
    .ToDictionary(x => x.Name, x => x.Val);

var jsonSerialiser = new JavaScriptSerializer();
var json = jsonSerialiser.Serialize(combined);

This will result in the following json

{ "account-Ind" : "A", ... }

NtFreX
  • 10,379
  • 2
  • 43
  • 63
  • I am facing an error saying - "an item with the same key has already been added". I am using a foreach loop, so for first time its working fine but in the second iteration it is throwing error. Is there any way that I can handle the error while using Zip? – shyam Jun 29 '17 at 12:49
  • @shyam I do not know that directly. You could ask a new question – NtFreX Jun 29 '17 at 12:54
  • I got the answer. I was not putting new keywork within the foreach loop. Thanks. – shyam Jun 29 '17 at 12:55