0

我有一个非常简单的结构,看起来像这样:

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 }
        };

我想重塑这个结构,以便当它被序列化为 json 时,结果应该如下所示,每个名称一个数组:

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

我的 linq 查询如下所示:

   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})
                };

这几乎可以工作,但是我得到了一个额外的“级别”数组,所以当序列化为 json 时,结果如下所示:

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

我在这里做错了什么?

4

1 回答 1

2

你几乎到过那里,而不是

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

简单地:

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

您只是在最后添加了不必要的数组级别。

于 2012-06-08T06:58:42.370 回答