c# - 如何优化以下 linq to object 查询

标签 c# asp.net linq linq-to-objects

我有一个具有以下属性的可枚举类

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

对于“字符串”结果:

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

关于c# - 如何优化以下 linq to object 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30886942/

相关文章:

asp.net - 访问路径 'c:\inetpub\wwwroot\myapp\App_Data'被拒绝

c# - 将两个 linq 查询放入一个列表框中

arrays - 如何生成多个数组的所有排列/组合?

c# - 接口(interface) "not marked with serializable attribute"异常

.NET 5.0 上 Outlook Automation 的 C# Marshal.GetActiveObject() 替代方案

c# - 使用 WebAPI 流式传输大文件(通过 IIS 超过 2GB)

asp.net - ASP.NET 中的确认消息

c# - 将缺失的月份计数为零 (0) 并填充到数据表中

c# - 如何使用撒克逊将文档类型参数传递给 xslt?

mysql - 我应该使用哪种连接? 【EF4.0代码优先】