比较类型的成员 - 计算成员之间的差异

时间:2012-11-21 15:00:07

标签: c# linq list

我有以下类型:

public class Parts
{
    public string PartNo { get; set; }
    public decimal Price { get; set; }
}

我想要做的是比较价格或每个部分与最便宜的部分,并显示百分比的差异。

这是我到目前为止所尝试过的并且有效:

        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");

这输出以下内容:

part1: 8, 0
part1: 10, 25.00
part1: 12, 50.0

这显示了每个部分的价格上涨,这就是我想要实现的目标,但我想知道是否有更好的方法来计算百分比的价格差异(例如,使用LINQ查询)或以任何其他方式

由于

3 个答案:

答案 0 :(得分:3)

我会计算差异作为第一步。

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);

答案 1 :(得分:2)

// 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});

.Skip(1)是可选的。您可能不想比较最便宜的价格。

答案 2 :(得分:1)

蒂姆打败了我,但是用select来创建你的字符串

void Main()
{
        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 lowest = parts.Min(p => p.Price );

        var result = parts.Select (p => string.Format("Part #:{0} {1} -> {2}", p.PartNo, p.Price,  ((p.Price/lowest)-1)*100 ));

      result.ToList()
            .ForEach(rs => Console.WriteLine (rs));
        /*
Part #:part1 10 -> 25.00
Part #:part1 8 -> 0
Part #:part1 12 -> 50.0
*/


}

// Define other methods and classes here
public class Part
{
    public string PartNo { get; set; }
    public decimal Price { get; set; }
}