I have the following type:
public class Parts
{
public string PartNo { get; set; }
public decimal Price { get; set; }
}
what I would like to do is to compare the price or each part with the cheapest one and display the difference in percentage.
This is what I have tried so far and it works:
var part1 = new Part {PartNo = "part1", Price = 10};
var part2 = new Part {PartNo = "part1", Price = 8};
var part3 = new Part {PartNo = "part1", Price = 12};
var parts = new List<Part> {part1, part2, part3};
var list = from p in parts
orderby p.Price ascending
select p;
var sb = new StringBuilder();
var counter = 0;
decimal firstPrice=0;
foreach (Part p in list)
{
if (counter == 0)
{
firstPrice = p.Price;
}
sb.Append(p.PartNo + ": " + p.Price + "," + ((p.Price/firstPrice)-1)*100 + Environment.NewLine);
counter++;
}
Console.WriteLine(sb.ToString(), "Parts List");
This outputs the following:
part1: 8, 0
part1: 10, 25.00
part1: 12, 50.0
This shows the price increase for each each part, and that is what I am trying to achieve but I was wondering is there a better way of calculating the price difference in percentage (e.g. with a LINQ query) or in any other way.
Thanks
I would calculate the difference as first step.
var cheapestPrice = parts.Min(p => p.Price);
var list = parts.Select(p => new {
Part = p,
DiffPercentage = ((p.Price - cheapestPrice) / cheapestPrice) * 100
});
foreach (var p in list)
Console.WriteLine("{0}: {1},{2}%", p.Part.PartNo, p.Part.Price, p.DiffPercentage);
// list defined as sorted by price ascending as per the code
var list = parts.OrderBy(p => p.Price); // less verbose way of saying the same
var firstPrice = list.First().Price;
var differences = list.Skip(1).Select(s => new {Part = s, PercentageDiff = (s.Price/firstPrice - 1)*100});
The .Skip(1) is optional. You may not want to compare cheapest price to itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With