首页 > 解决方案 > 如何将来自其他两个列表 C# 的元素按升序存储在列表中?

问题描述

我遇到的问题是以升序显示列表中的项目。我了解造成此问题的问题,即我将 caccounts 添加到列表中,然后将 saccounts 添加到列表中,但我不确定是否有任何其他方法可以做到这一点。结果应该是以取决于用户的创建顺序显示帐户。因此,如下图所示,它首先存储和显示所有创建的支票账户,然后是不正确的储蓄账户。它应该按照它们的创建顺序显示。正如您从下图中看到的那样,这些项目是乱序的。它应该首先显示储蓄账户 1,然后是支票账户 2,依此类推。

这是显示项目的方式

这是将项目添加到此列表并产生问题的代码

List<Account> accounts = new List<Account>();

accounts.AddRange(caccounts);
accounts.AddRange(saccounts);

foreach (Account account in accounts)
{
    List<Transaction> transactions = account.closeMonth();

    allTransactions.AddRange(transactions);
}

此代码显示了我要添加 saccounts 和 caccounts 的列表

List<SavingsAccount> saccounts = new List<SavingsAccount>();
List<CheckingAccount> caccounts = new List<CheckingAccount>();
List<Transaction> allTransactions = new List<Transaction>();

这是我在支票类和储蓄类中的代码,它覆盖了抽象账户类中的关闭月份

public override List<Transaction> closeMonth()
{
    var transactions = new List<Transaction>();

    var endString = new Transaction();

    string reportString = ("Checking account: " + AccountID.ToString() + 
        " has a balance of $" + endingBalance.ToString());

    endString.EndOfMonth = reportString;
    transactions.Add(endString);

    return transactions;
}

这是 AccountID 的属性,我在支票和储蓄类中有这个

class SavingsAccount : Account
{
    public override int AccountID { get; set; }
}

最初创建帐户时,这是分配 AccountID 的代码

if (checkingRadioButton1.Checked == true)
{
    _nextIndex++;
    transactionLabel5.Text = "Checking Account: #" + _nextIndex + 
        " created with a starting balance of $" + balance;
    accountTextBox1.Text = "" + _nextIndex;
    caccounts.Add(new CheckingAccount(balance)
    {
        AccountID = _nextIndex,
        Student = isStudent
    });
}
else if (savingsRadioButton2.Checked == true)
{
    _nextIndex++;
    transactionLabel5.Text = "Savings Account: #" + _nextIndex + 
        "   created with a starting balance of $" + balance;
    accountTextBox1.Text = "" + _nextIndex;
    saccounts.Add(new SavingsAccount(balance)
    {
        AccountID = _nextIndex,
        Senior = isSenior
    });
}

标签: c#

解决方案


您可以OrderBy在收藏中使用。

var orderedTransactions = allTransactions.OrderBy(x=>x.AccountId).ToList();

当然,您需要在对象中具有该 CreateDate 或您想要订购的任何属性。


推荐阅读