2015-06-17 35 views
1

如何優化下面的LINQ to對象查詢

Sku 

Itemid 

colorid 

size_id 

例如,具有以下屬性enumarable類:

sku1 item1 color1 size1 

sku1 item2 color2 size1 

sku2 item2 color3 size1 

這裏SKU可以重複多次

我想改變結構到類似的東西 Sku1 comma_seperated_colors comma_seperated_size

所以SKU1輸出應該是

SKU1顏色2,顏色1尺寸1

目前我在做,像

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。 由於需要多次掃描,現在這需要很長時間。 我可以讓這個更快嗎?

在此先感謝

回答

3

那麼,你不能使用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 
       }); 

,併爲 「字符串」 的結果:

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