如何使用LINQ在列表中生成重复项?

Kar*_*hik 11 c# linq

这是我用过的LINQ查询

var result = (from price in inventoryDb.Pricing.AsNoTracking()               
              where price.Quantity > 0m
              select new
              {
                 TagNo = price.TagNo,
                 SellingRate = price.SellingRate,
                 Quantity = price.Quantity           
              }).ToList();
Run Code Online (Sandbox Code Playgroud)

基于Quantity我需要在列表中生成重复项的值.

输出:

result = [0]{TagNo="100", SellingRate=1500.00, Quantity=1}
         [1]{TagNo="101", SellingRate=1600.00, Quantity=2}
Run Code Online (Sandbox Code Playgroud)

预期结果:

result = [0]{TagNo="100", SellingRate=1500.00}
         [1]{TagNo="101", SellingRate=1600.00}
         [2]{TagNo="101", SellingRate=1600.00}
Run Code Online (Sandbox Code Playgroud)

Tim*_*ter 9

你可以使用Enumerable.SelectMany+ Enumerable.Range:

var result = inventoryDb.Pricing.AsNoTracking()
    .Where(p => p.Quantity > 0m)
    .SelectMany(p => Enumerable.Range(0, p.Quantity)
        .Select(i => new
              {
                 TagNo = p.TagNo,
                 SellingRate = p.SellingRate      
              }))
    .ToList();
Run Code Online (Sandbox Code Playgroud)

如果您的LINQ提供程序(fe Linq-To-Entities)不支持,最简单的方法是使用Linq-To-Objects.为避免将所有内容加载到内存中,您应该AsEnumerable在以下后使用Where:

var result = inventoryDb.Pricing.AsNoTracking()
    .Where(p => p.Quantity > 0m)
    .AsEnumerable()
    .SelectMany(p => Enumerable.Range(0, p.Quantity)
        .Select(i => new
              {
                 TagNo = p.TagNo,
                 SellingRate = p.SellingRate      
              }))
    .ToList();
Run Code Online (Sandbox Code Playgroud)


Gil*_*een 5

与查询语法保持一致,只需添加 a ,Enumerable.Repeat如下所示:

var result = (from price in inventoryDb.Pricing.AsNoTracking()
              where price.Quantity > 0m
              from dup in Enumerable.Repeat(0,price.Quantity)
              select new
              {
                 TagNo = price.TagNo,
                 SellingRate = price.SellingRate,          
              }).ToList();
Run Code Online (Sandbox Code Playgroud)

如果确实 linq toEntity 不支持,则添加AsEnumerable如下:

var result = (from price in inventoryDb.Pricing.AsNoTracking()
                                               .Where(p => p.Quantity > 0m)
                                               .AsEnumerable() //Loads only the filtered items to memory            
              from dup in Enumerable.Repeat(0,price.Quantity)
              select new
              {
                 TagNo = price.TagNo,
                 SellingRate = price.SellingRate,          
              }).ToList();
Run Code Online (Sandbox Code Playgroud)

您也可以使用Enumerable.Range,但因为您不使用该集合的价值(在我看来,它也更好地描述了您正在做的事情),我决定只使用Repeat