5

Hey folks, hope you've all had a good break over the holidays.

I've created a WebService which returns a list of cities and companies within those cities as a JSON string using LINQ/JavaScriptSerializer.

My code is roughly

var data = from c in db.Companies
           group c by c.City into cities
           select new
           {
               city = cities.Key,
               companies = from company in cities
                     select company.Name
           };

JavaScriptSerializer jss = new JavaScriptSerializer();
return jss.Serialize(data);

That produces the following JSON string

[
  {"city":"Auckland","companies":["Company1","Company2"]},
  {"city":"Wellington","companies":["Company3","Company4","Company5"]}
]

However I want to make the city the key so I can easily search by it

For example

[
  "Auckland" : {"companies":["Company1","Company2"]},
  "Wellington" : {"companies":["Company3","Company4","Company5"]}
]

Any ideas?

2
  • I don't think that's even valid JSON. Are you sur you don't mean curly brackets instead of square brackets? Commented Jan 23, 2011 at 9:39
  • Hey @Mark, are you referring to the 2nd one? I manually typed that so apologies for the error. Commented Jan 23, 2011 at 9:48

1 Answer 1

8

Just an idea... try

var data = db.Companies
             .GroupBy(c => c.City)
             .ToDictionary(g => g.Key,
                           g => new { companies = g.Select(c => c.Name) });

So this will build a Dictionary<string, xxx> where xxx is an anonymous type with a single property, "companies" which is a sequence of company names.

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

4 Comments

Thanks Jon, I'm getting an exception though Error 2 Argument 3: cannot convert from 'AnonymousType#1' to 'System.Collections.Generic.IEqualityComparer<string>'
@Marko I think I see the issue there - try the update? (Jon- hope you don't mind me hacking away ;p)
@Marc: Thanks for that :) Will edit again just to try to get rid of the scrollbar...
P.S. I'm not sure the title makes too much sense so edit away if you have a better one.

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.