0

I have a pretty simple structure that looks something like this:

var list = new List<CategoryInTimeItem>
        {
            new CategoryInTimeItem { Name = "Food", Year = 2012, Month = 1, Amount = 100 },
            new CategoryInTimeItem { Name = "Food", Year = 2012, Month = 2, Amount = 110 },
            new CategoryInTimeItem { Name = "Food", Year = 2012, Month = 3, Amount = 130 },
            new CategoryInTimeItem { Name = "Food", Year = 2012, Month = 4, Amount = 130 },
            new CategoryInTimeItem { Name = "Transport", Year = 2012, Month = 1, Amount = 1000 },
            new CategoryInTimeItem { Name = "Transport", Year = 2012, Month = 2, Amount = 1101 },
            new CategoryInTimeItem { Name = "Transport", Year = 2012, Month = 3, Amount = 1301 },
            new CategoryInTimeItem { Name = "Transport", Year = 2012, Month = 4, Amount = 1301 }
        };

I want to reshape this structure so that when it get's serialized to json the result should look like this, one array for each name:

[
[["2012-1", 100], ["2012-2", 110], ["2012-3", 130], ["2012-4", 130]],
[["2012-1", 1000], ["2012-2", 1101], ["2012-3", 1301], ["2012-4", 1301]]
]

My linq query looks like this:

   result.Values = 
                from d in list
                orderby d.Name , d.Year , d.Month
                group d by d.Name
                into grp
                select new[]
                {
                    grp.Select(y => new object[] {y.DateName, y.Amount})
                };

This almost works, however I get an extra "level" of arrays, so when serialized to json the result looks like this:

[
[[["2012-1", 100], ["2012-2", 110], ["2012-3", 130], ["2012-4", 130]]],
[[["2012-1", 1000], ["2012-2", 1101], ["2012-3", 1301], ["2012-4", 1301]]]
]

What am I doing wrong here?

1 Answer 1

2

You've almost been there, just instead of

from d in list
...
select new[]
{
    grp.Select(y => new object[] {y.DateName, y.Amount})
}

simply:

from d in list
...
select grp.Select(y => new object[] {y.DateName, y.Amount}).ToList()

You just added an unnecessary level of array at the end.

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

Comments

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.