Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate duplicate items in a list using LINQ?

Tags:

c#

linq

this is LINQ query I have used

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

Based on the Quantity value I need to generate duplicate items in the list.

Output :

result = [0]{TagNo="100", SellingRate=1500.00, Quantity=1}
         [1]{TagNo="101", SellingRate=1600.00, Quantity=2}

Expected Result:

result = [0]{TagNo="100", SellingRate=1500.00}
         [1]{TagNo="101", SellingRate=1600.00}
         [2]{TagNo="101", SellingRate=1600.00}
like image 359
Karthik Arthik Avatar asked Oct 07 '16 09:10

Karthik Arthik


1 Answers

You can use 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();

If that's not supported by your LINQ provider (f.e. Linq-To-Entities), the easiest is to use Linq-To-Objects. To avoid that all is loaded into memory you should use AsEnumerable after the 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();
like image 197
Tim Schmelter Avatar answered Oct 06 '22 01:10

Tim Schmelter