如何优化以下 linq to object 查询

How To optimise following linq to object query

我有一个数不胜数的 class 有以下 属性

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

然后选择独特的 SKU。 现在由于需要多次扫描,这需要很长时间。 我可以让它更快吗??

提前致谢

嗯,你不能使用 groupby 吗?

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

对于 "string" 结果:

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