我有以下类型:
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 查询)或以任何其他方式。
谢谢