我正在尝试构建这个对象:
[
{
"color" : "red",
"category" : "tshirts",
"Items" : [
{
"r" : 1,
"n" : "name: E624E",
"s" : 9819217.000
}, {
"r" : 2,
"n" : "name: 00F37",
"s" : 9791564.000
}, {
"r" : 3,
"n" : "name: 75B02",
"s" : 9790543.000
}, {
"r" : 4,
"n" : "name: 08864",
"s" : 9485392.000
}
]
},
{
"color" : "red",
"category" : "shoes",
"Items" : [
{
"r" : 1,
"n" : "name: 20272",
"s" : 9949541.000
}, {
"r" : 2,
"n" : "name: 1E496",
"s" : 9926730.000
}, {
"r" : 3,
"n" : "name: 00F37",
"s" : 9926493.000
}, {
"r" : 4,
"n" : "name: 48A44",
"s" : 9923929.000
}
]
}
]
我构建它的方式是使用 Linq,遍历颜色和类别的集合:
var colors = ctx.Colors.Select(x => x.Color).Distinct().ToList();
foreach (var color in colors)
{
var categories = ctx.Categories.Where(x => x.Color == color).Select(x => x.Category).Distinct().ToList();
foreach (var cat in categories)
{
List<ItemAttribute> iattr = (from i in ctx.Item
where i.Color == color && i.Category == cat
select new ItemAttribute {
r = i.R,
n = i.N,
s = i.S
}).ToList();
this.ItemStuff.Add(iattr);
}
}
这行得通,我得到了预期的结果,但性能很糟糕而且看起来很冗长。
任何人都可以提供一些改进这一点的见解吗?