0

My intention is to use LINQ query then return JSON for MVC controller.

format I want to achieve:

[{ 
   "A" : {"Count": 2 },
   "B" : {"Count": 7 },
}]

or

[{ 
   "A" : [{"Count": 2 }],
   "B" : [{"Count": 7 }],
}]

But so far I only can make it like this:

[{ 
   {"MG":"A", "Count": 2 },
   {"MG":"B", "Count": 7 }
}]

And I try something like below, it get error

Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access.

public JsonResult groupByTable()
{
    IQueryable<tblSAPMessage> v = sapMessages();
    var data = v.GroupBy(g => g.MaterialGroup)
        .Select(g => new { g.Key.ToString() = new {
                    Count = g.Count()
                }});
    return Json(data, JsonRequestBehavior.AllowGet);
}

Appreciate if someone can point me to correct direction. Thanks !

2 Answers 2

1

if i understand correctly you need dynamic property names. You could achieve it only using Expando Object

You could try something around these lines.

dynamic mytype = new ExpandoObject();
var data = v.GroupBy(g => g.MaterialGroup)
        .Select(g => (IDictionary<string, object>) mytype.Add(g.Key.ToString(),
        new {Count =  g.Count()}));

you could look at these answers for more inspiration Dynamic properties

Sign up to request clarification or add additional context in comments.

1 Comment

I feel like I got your idea, but somehow, I play around with the code, still not able to make it. Still having same error.
0

you can use json.net / newtonsoft to create a json object

using Json.net
var countObject = new JObject ();
countObject.Add("count",2);
var jsonObject = new JObject();
jsonObject.Add("a", countObject);

2 Comments

Thanks Michael, yr method will need a loop, but i look for method using linq.
Have you tried using the linq foreach?msdn.microsoft.com/en-us/library/bwabdf9z(v=vs.110).aspx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.