Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare members of a type - calculate the difference between members

Tags:

c#

list

linq

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

like image 665
03Usr Avatar asked Jan 18 '26 12:01

03Usr


2 Answers

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);
like image 136
Tim Schmelter Avatar answered Jan 21 '26 03:01

Tim Schmelter


// 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.

like image 25
weston Avatar answered Jan 21 '26 04:01

weston



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!