[英]How to find the key of a dictionary when the value is a list of objects in C#?
[英]How to update value in dictionary if second parameter of it is list of objects C#
如果第二个参数是对象列表,如何更改字典中的值?
我有这个模型:
public class Account
{
public string AccountType { get; set; }
public string AccountName { get; set; }
public BigInteger AccountNumber { get; set; }
public decimal Balance { get; set; }
public decimal AvailableBalance { get; set; }
public string Currency { get; set; }
public decimal InterestRate { get; set; }
}
我做了一个字典,其中的键是字符串,值是Account的对象类型列表:
Dictionary<string, List<Account>> dictionaries = new Dictionary<string, List<Account>>();
我已经提交了带有一些自定义数据的帐户列表:
List<Account> NMoAccounts = new List<Account>(){
new Account {AccountName="Credit card 1", AccountNumber=5234567890, AccountType="Credit card", AvailableBalance=234.4m, Balance=432.64m, Currency="euro", InterestRate=1.5m},
new Account {AccountName="Credit card 3", AccountNumber=1357924680, AccountType="Credit card", AvailableBalance=24.06m, Balance=-32.123m, Currency="euro", InterestRate=1.5m},
new Account {AccountName="Current card 10", AccountNumber=4567890123, AccountType="Current card", AvailableBalance=1.8m, Balance=2.3m, Currency="euro", InterestRate=1.5m},
new Account {AccountName="Credit card 5", AccountNumber=857624621, AccountType="Credit card", AvailableBalance=31.4m, Balance=-132.123m, Currency="euro", InterestRate=1.5m}
};
dictionaries.Add("user", NMoAccounts);
我想做这样的事情:
就像我在模拟银行帐户之间的资金交易一样。
我可以用字典执行此操作吗? 如果有人有类似主题的教程,我将不胜感激。
很简单:
// find list in dictionary
List<Account> acctList = dictionaries[keyString];
// search account in list
Acount account = acctList.FirstOrDefault(a => a.AccountName = acctName);
if(account == null) // some error handling here
// modify account
accout.Balance -= 5;
因为字典存储参考,并且列表也包含参考,所以您可以直接修改这些对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.