C# 如果字典的第二个参数是对象列表C,如何更新字典中的值#
如果我的第二个参数是对象列表,我如何更改字典中的值 我有这个模型:C# 如果字典的第二个参数是对象列表C,如何更新字典中的值#,c#,dictionary,data-structures,C#,Dictionary,Data Structures,如果我的第二个参数是对象列表,我如何更改字典中的值 我有这个模型: public class Account { public string AccountType { get; set; } public string AccountName { get; set; } public BigInteger AccountNumber { get; set; } public decimal Balance { get; set; } public dec
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; }
}
我制作了一个字典,其中键是字符串,值是对象列表帐户类型:
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);
List账户=新列表(){
新账户{AccountName=“信用卡1”,AccountNumber=5234567890,AccountType=“信用卡”,可用余额=2.344亿,余额=4.3264亿,货币=euro,利率=150万},
新账户{AccountName=“信用卡3”,AccountNumber=1357924680,AccountType=“信用卡”,可用余额=246万,余额=32.123万,货币=euro,利率=150万},
新账户{AccountName=“当前卡10”,AccountNumber=4567890123,AccountType=“当前卡”,可用余额=180万,余额=230万,货币=euro,利率=150万},
新账户{AccountName=“信用卡5”,AccountNumber=857624621,AccountType=“信用卡”,可用余额=3140万,余额=1.32亿,货币=欧元,利率=150万}
};
字典。添加(“用户”,即帐户);
我想这样做:
我可以用字典做这个操作吗?如果有人有类似主题的教程,我将不胜感激。这很简单:
// 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;
//在字典中查找列表
List acctList=字典[keyString];
//在列表中搜索帐户
Acount account=acctList.FirstOrDefault(a=>a.AccountName=acctName);
if(account==null)//这里有一些错误处理
//修改帐户
账户余额-=5;
因为字典存储引用,列表也包含引用,所以您可以直接修改这些对象。这是一篇关于如何使用字典的好文章。你应该把字典命名为
accountListDict
(单数)你可以使用吗?如果是这样,您可以通过以下方式轻松获得具有特定帐号的帐户:dictionaries[“user”].Single(account=>account.AccountNumber==[theProvidedAccountNumber])代码>--注意,如果没有具有该号码的帐户,如果有多个具有该号码的帐户,则会引发异常。根据您的需要,您可以更改Single
的SingleOrDefault
、First
或FirstOrDefault
或类似内容。感谢您的回答。。。请允许我再问一个问题。。。是否可以在原始字典中保存更改的值?因为本例更改的是帐户的副本,而不是原始帐户@科赫博士