簡體   English   中英

如果字典的第二個參數是對象列表,則如何更新字典中的值

[英]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);

我想做這樣的事情:

  1. 通過鍵獲取目錄。
  2. 例如,查找具有兩個帳號的帳號(帳號的值由客戶傳遞):例如該詞典中的5234567890和1357924680。
  3. 減少5號5234567890的帳戶余額(此值也由客戶傳遞),並增加5號1357924680的帳戶余額。

就像我在模擬銀行帳戶之間的資金交易一樣。

我可以用字典執行此操作嗎? 如果有人有類似主題的教程,我將不勝感激。

很簡單:

// 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM