How To optimise following linq to object query

74 views Asked by At

I have a enumarable class having following property

 Sku

 Itemid

 colorid

 size_id

eg:

sku1  item1 color1 size1

sku1  item2 color2 size1

sku2  item2 color3 size1

here sku can be repeated multiple times

I want to change the structure to something like that Sku1 comma_seperated_colors comma_seperated_size

so for sku1 the output should be

sku1 color2,color1 size1

currently I am doing that like

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

and then selecting unique skus. now this is taking very long due to multiple scan that is needed. Can I make this faster??

Thanks in advance

1

There are 1 answers

0
Raphaël Althaus On BEST ANSWER

Well, couldn't you use a 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
                 });

and for the "string" result :

var result = item3.Select(m.SKU + " " + m.colors + " " + m.sizes).ToList();

or

var result = item3.Select(m => string.Format("{0} {1} {2}", m.SKU, m.colors, m.sizes)).ToList();