Home > Net >  How to display product using group by prices in c# console app
How to display product using group by prices in c# console app

Time:10-29

I have list of products which has id, name and price. I want to show it in console using prices such as

Price 1 to 100 --list of products

price 101 to 200 --list of products and it so on till last highest price. I need to determine at runtime how many segments I need to create based upon highest price.

CodePudding user response:

If you have a list called products that have a property called Price you could use a basic Linq expression with OrderBy and Where

Edit: now that I understand your question better, you could create a new list for each segment of 100's.

so something like this:

products = products.OrderBy(x => x.Price).ToList();
var subProducts = products.Where(x => x.Price > 0 && x.Price < 100).ToList();
// then print each item in the list here.
// then do the next segment
subProducts = products.Where(x => x.Price >= 100 && x.Price < 200).ToList();

and you could put this basic format in a loop and then iterate through by the 100's to get each segment.

CodePudding user response:

There are two problems to solve here. First, you need to figure out, for any given price, how to categorize it into a price range. The information you've given in your post isn't quite specific enough unless all your prices are in whole numbers, but I'll make an educated guess here.

// Model
record ProductPriceRange(decimal Low, decimal High);

// Desired behavior
GetPriceRange(0.01m).Should().Be(new ProductPriceRange(0.01m, 100m));
GetPriceRange(100m).Should().Be(new ProductPriceRange(0.01m, 100m));
GetPriceRange(100.01m).Should().Be(new ProductPriceRange(100.01m, 200m));

// Implementation
ProductPriceRange GetPriceRange(decimal price)
{
    var groupBasis = (int)(((price - 0.01m) / 100)) * 100   0.01m;
    return new ProductPriceRange(groupBasis, groupBasis   99.99m);
}

Then your grouping code can look something like this:

var productGroups =
    from p in products
    group p by GetPriceRange(p.Price) into g
    select new {
        PriceRange = g.Key,
        Products = g.ToList()
    };
foreach (var g in productGroups)
{
    Console.WriteLine($"{g.PriceRange.Low} - {g.PriceRange.High}: {string.Join(", ", g.Products)}");
}

Sample output:

0.01 - 100.00: Product { Price = 0.01 }, Product { Price = 99.99 }, Product { Price = 100 }
100.01 - 200.00: Product { Price = 100.01 }, Product { Price = 199.99 }, Product { Price = 200 }
200.01 - 300.00: Product { Price = 200.01 }

CodePudding user response:

Try the following:

var query = products
   .GroupBy(p => (int)(p.Price / 100))
   .OrderBy(g => g.Key)
   .Select(g => new {
      Lower = g.Min(x => x.Price),
      Higher = g.Max(x => x.Price),
      Items = g.OrderBy(x => x.Price).ToList())
   })
   .ToList();

It will return list of lists.

  • Related