C#中的列表或字典

Pra*_*del -7 c#

我需要两个列表作为输出,其中一个是索引列表,另一个是相应的值,直到条件满足为止.

//initializing the first value of TotalDebts
double TotalDebts = 30000;
for (int i = 0; i < 250; i++)
{
    if (TotalDebts > 0)
    {
        double DebtsLessIncome = Convert.ToDouble(TotalDebts - 1000);
        double InterestCharged = Convert.ToDouble((DebtsLessIncome * 5) / 100);
        double InterestDebt = Convert.ToDouble(DebtsLessIncome + InterestCharged);
        double InterestDebtMLE = Convert.ToDouble(InterestDebt + 500);
        double TotalDebts = Convert.ToDouble(InterestDebtMLE);
        //how to add TotalDebts in list or dictionary from each loop as index 0,1,2 and so on 
        List<double> AllDebits = new List<double>();
        AllDebits.Add(TotalDebts);
        // how to retrieve each index and value and store index in one list and value in second list
    }
}  
Run Code Online (Sandbox Code Playgroud)

fub*_*ubo 5

基于"如何检索每个索引和值" - 我假设你想通过索引(=年?)访问数据 - 字典可以正常工作.

double TotalDebts = 30000;
Dictionary<int, double> dResult = new Dictionary<int, double>();
for (int i = 0; i < 250; i++)
{
    if (TotalDebts > 0)
    {
        double DebtsLessIncome = Convert.ToDouble(TotalDebts - 1000);
        double InterestCharged = Convert.ToDouble((DebtsLessIncome * 5) / 100);
        double InterestDebt = Convert.ToDouble(DebtsLessIncome + InterestCharged);
        double InterestDebtMLE = Convert.ToDouble(InterestDebt + 500);
        TotalDebts = Convert.ToDouble(InterestDebtMLE);
        dResult.Add(i, TotalDebts);
    }
}  
Run Code Online (Sandbox Code Playgroud)

笔记

  • Dictionary不支持有序迭代,因此如果您需要输出年/债务对列表,请使用其他一些数据结构(即List<KeyValuePair<int, decimal>>).
  • 通常一个人会用decimal钱而不是float/ double.

更新(将字典拆分为2个列表)

List<int> lIndex = dResult.Select(x => x.Key).ToList();
List<double> lDepts = dResult.Select(x => x.Value).ToList();
Run Code Online (Sandbox Code Playgroud)