3

我有以下类型:

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 查询)或以任何其他方式。

谢谢

4

3 回答 3

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);
于 2012-11-21T15:07:25.960 回答
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)是可选的。您可能不想将最便宜的价格与自己进行比较。

于 2012-11-21T15:11:18.870 回答
1

蒂姆打败了我,但使用选择来创建你的字符串

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; }
}
于 2012-11-21T15:11:02.687 回答