tags:

views:

161

answers:

3

I am attempting to use linq to shape list of data into a particular shape to be returned as Json from an ajax call.

Given this data:

       var data = new List<string>();
       data.Add("One");
       data.Add("Two");
       data.Add("Three");

And this code: ** Which is not correct and is what needs to be fixed!! **

       var shaped = data.Select(c =>
            new { c = c }
        ).ToList();

       serializer.Serialize(shaped,sb);
       string desiredResult = sb.ToString();

I would like desiredResult to be:

{ "One": "One", "Two": "Two", "Three": "Three" }

but it is currently:

{ "c" : "One" },{ "c" : "Two" } etc

One problem is that on the left side of the object initializer I want the value of c, not c itself...

+1  A: 

In json, the "c" in "c" : "One" is the property name. And in the C# world, you can't create property names on the fly (ignoring System.ComponentModel).

Basically, I don't think you can do what you want.

Marc Gravell
+1  A: 

Solution offered for correctness, not performance.

        List<string> data = new List<string>()
        {
            "One",
            "Two",
            "Three"
        };

        string result =
            "{ "
            +
            string.Join(", ", data
              .Select(c => @"""" + c + @""": """ + c + @"""")
              .ToArray()
            ) + " }";
David B
+1  A: 

What about using JSON.NET ?

mathieu