Brian Davis
Brian Davis

Reputation: 817

Creating a json-style inside a linq select statement

In my MVC controller, I have the following linq query (which works fine):

var result = from li in lineItems
             join r in rates on li.something = r.something
             select new
             {
                 li.something
                 li.somethingElse
                 li.another
                 r.something
                 r.somethingElse
                 r.rate1
                 r.rate2
                 r.rate3
                 r.rate4
             };

return JSON(result.ToList(), JsonRequestBehavior.AllowGet);

And that generates a flat object just fine. However, what I really need is for the rates to be an object of their own, one layer deeper, like this:

{
    li.something
    li.somethingElse
    li.another
    r.something
    r.somethingElse
    rates = {
                {id = "1", value = r.rate1}
                {id = "2", value = r.rate2}
                {id = "3", value = r.rate3}
                {id = "4", value = r.rate4}
            }
}

I'm having difficulty getting the C# syntax right to make that happen. Hardcoding the id is fine. I will always only have rate 1 2 3 and 4.

Upvotes: 1

Views: 320

Answers (2)

Brian Davis
Brian Davis

Reputation: 817

I ended up doing this:

rates = new
{
    Rate1 = new {id = "1", value = r.rate1}
    Rate2 = new {id = "2", value = r.rate2}
    Rate3 = new {id = "3", value = r.rate3}
    Rate4 = new {id = "4", value = r.rate4}
}

Which didn't throw any errors. It named the JSON which I didn't really need but I guess it didn't hurt anything either.

Upvotes: 0

Mukesh
Mukesh

Reputation: 410

You can define 'rates' property as anonymous array of object, please see below sample for reference.

{
    li.something,
    li.somethingElse,
    li.another,
    r.something,
    r.somethingElse,
    rates = new[]{
                new {id = "1", value = r.rate1},
                new {id = "2", value = r.rate2},
                new {id = "3", value = r.rate3},
                new {id = "4", value = r.rate4}
            }
}

Upvotes: 3

Related Questions