我有一个具有以下属性的可强制类
Sku
Itemid
colorid
size_id
例如:
sku1 item1 color1 size1
sku1 item2 color2 size1
sku2 item2 color3 size1
这里sku可以重复多次
我想将结构更改为类似的结构 Sku1 comma_seperated_colors comma_seperated_size
所以对于sku1,输出应该是
sku1 color2,color1 size1
目前我正在这样做
var item3 = (from iq in items2 select new {
iq.SKU,
AllColors = string.Join(",", (from i in items2 where i.SKU == iq.SKU select i.color_class).DefaultIfEmpty().ToArray()),
AllSizes = string.Join(",", (from i in items2 where i.SKU == iq.SKU select i.size).Distinct().DefaultIfEmpty().ToArray())
});
然后选择独特的skus。 现在这需要很长时间,因为需要进行多次扫描。 我可以加快速度吗?
提前致谢
答案 0 :(得分:3)
嗯,你不能使用群组吗?
var item3 = items.GroupBy (m => m.SKU)
.Select(g => new {
SKU = g.Key,
colors = string.Join("," , g.Select(m => m.color_class)
.Distinct()),//you could do a .OrderBy(m => m) after the distinct
sizes = string.Join(",", g.Select(m => m.size)
.Distinct())//you could do a .OrderBy(m => m) after the distinct
});
和"字符串"结果:
var result = item3.Select(m.SKU + " " + m.colors + " " + m.sizes).ToList();
或
var result = item3.Select(m => string.Format("{0} {1} {2}", m.SKU, m.colors, m.sizes)).ToList();