我想使用C#根据板材计算电费,如下表所示
SlabFrom SlabTo Rate
0 100 5.00
101 500 10.00
501 Null 15.00板数可以更改,需要最佳解决方案来计算总成本
根据总使用量。如果总使用量为1,000,则应计算:
(100 X 5) + (400 X 10) + (500 X 15) = 12,000
public class Cost
{
public decimal SlabFrom { get; set; }
public decimal SlabTo { get; set; }
public bool SlabHour { get; set; }
public decimal RatePerUnit { get; set; }
}
var rates = new List<Cost>
{
new Cost()
{
SlabFrom = 0,
SlabTo = 100,
RatePerUnit = 5
},
new Cost()
{
SlabFrom = 101,
SlabTo = 500,
RatePerUnit = 10
},
new Cost()
{
SlabFrom = 501,
SlabTo = 1000,
RatePerUnit = 15
},
new Cost()
{
SlabFrom = 1001,
SlabTo = 1500,
RatePerUnit = 20
}
};发布于 2016-07-25 19:06:19
如果你只想要前3个
int usage = 503;
int total = usage < 100 ? usage * 5 : 500 + (usage < 500 ? (usage - 100) * 10 : 4000 + (usage - 500) * 15);
//4545如果你想要一个更通用的答案
顺便说一句,我用你的成本类来测试这个
decimal used = 1000;
decimal LastSlabto = 0;
decimal total = 0;
foreach (Cost rate in rates)
{
if (used > rate.SlabTo - LastSlabto)
total += (rate.SlabTo - LastSlabto) * rate.RatePerUnit;
else
{
total += used * rate.RatePerUnit;
used = 0;
break;
}
used -= rate.SlabTo - LastSlabto;
LastSlabto = rate.SlabTo;
} 发布于 2016-07-25 18:32:28
您可以这样做:
rates.TakeWhile(item => item.SlabFrom totalUsage)
.Sum(item => (double)((item.SlabTo > totalUsage ? totalUsage : item.SlabTo) - item.SlabFrom) * item.RatePerUnit);发布于 2016-07-25 19:19:28
尝尝这个
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
DataTable dt = new DataTable();
dt.Columns.Add("SlabFrom", typeof(int));
dt.Columns.Add("SlabTo", typeof(int));
dt.Columns["SlabTo"].AllowDBNull = true;
dt.Columns.Add("Rate", typeof(double));
dt.Rows.Add(new object[] {0,100,5.00});
dt.Rows.Add(new object[] {100,500,10.00});
dt.Rows.Add(new object[] {501,null,15.00});
int usage = 1500;
double cost = 0;
foreach(DataRow row in dt.AsEnumerable())
{
if(usage > 0)
{
if((row.Field<int?>("SlabTo") == null) || (usage < row.Field<int>("SlabTo")))
{
cost += usage * row.Field<double>("Rate");
usage = 0;
}
else
{
cost += (row.Field<int>("SlabTo") - row.Field<int>("SlabFrom")) * row.Field<double>("Rate");
usage -= (row.Field<int>("SlabTo") - row.Field<int>("SlabFrom"));
}
}
}
}
}
}https://stackoverflow.com/questions/38564991
复制相似问题