2015-04-02 16 views
0

如果我的第二個參數是對象列表,如何更改字典中的值?如何更新字典中的值,如果它的第二個參數是對象列表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; } 
} 

我做了一本字典,其中關鍵是字符串值是對象類型的帳戶列表:

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(該值也由客戶端傳遞),並增加餘額賬戶數爲1357924680 5.

喜歡的東西,我模擬銀行賬戶之間的金錢交易。

我可以用字典來做這個操作嗎?如果有人有一些類似主題的教程,我會感激不盡。

+0

這是一篇關於如何使用字典的好文章。 http://www.dotnetperls.com/dictionary。 – WorkSmarter 2015-04-02 09:03:59

+0

您應該爲您的詞典命名爲'accountListDict'(單數) – DrKoch 2015-04-02 09:07:13

+0

您是否允許使用[LINQ](https://msdn.microsoft.com/library/bb397933.aspx)?如果是這樣,你可以很容易地獲得具有特定帳號的帳號:'dictionaries [「user」]。Single(account => account.AccountNumber == [theProvidedAccountNumber]);' - 注意,這將拋出異常if如果該號碼有多個帳號,則沒有該號碼的帳號。你可以根據你的需要改變SingleOrDefault,First或FirstOrDefault或類似的東西。 – Corak 2015-04-02 09:09:26

回答

2

這是很簡單的:

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

因爲字典中存儲的引用,也該列表包含引用,您可以直接修改這些對象。

+0

感謝您的回答......如果我可能......還有一個問題是否可以將更改的值保存在原始字典中?由於此示例更改了帳戶的副本,而不是原始帳戶。 @DrKoch – 2015-04-02 11:41:57

相關問題