c# - 如何将来自其他两个列表 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
});
}
解决方案
您可以OrderBy
在收藏中使用。
var orderedTransactions = allTransactions.OrderBy(x=>x.AccountId).ToList();
当然,您需要在对象中具有该 CreateDate 或您想要订购的任何属性。
推荐阅读
- browser - 重新安装扩展程序后如何保留设备 ID 或任何 ID
- python-3.x - Pandas - 如果第二个字符串包含第一个字符串,则合并数据帧
- javascript - IOS浏览器中的javascript打印不打印对话框
- javascript - 网站缓存——浏览器缓存网站页面/js,避免用户看到网站更新
- java - 拆分后如何将值添加到同一字符串
- amazon-web-services - 在 S3 存储桶中拒绝具有特定标签值的 DeleteObject
- java - 如何在 AsyncTask 上使用 .getResources()?
- vue.js - vue 选择所有具有由计算方法生成的值的复选框
- java - 如何在 Tomcat 9 上使用 Log4J 配置应用程序日志记录?
- r - R:在 R 中的 VPN 之间切换