[英]C# initialize a dictionary then add to it later
我有一本字典,將從查詢結果中填充。 因此,在初始化字典時,我不知道哪些數據值將進入字典(盡管顯然我知道將使用哪種數據類型)。 我是C#的新手-如何設置?
用偽代碼,我想要的字典結構是:
{
"visa": [2.75, 3.33],
"mastercard": [1.00, 4.32],
...
}
這是我到目前為止的內容,但尚未編譯:
//initialize the dictionary but do not populate yet
Dictionary<string, List<decimal>> cardtype_total_amount;
//simulate getting the first card type from the db
string cardtype = "visa";
//initialize the "visa" key
if (!cardtype_total_amount.ContainsKey(cardtype)) cardtype_total_amount.Add(cardtype, new List<decimal>(){0, 0});
//simulate updating the values for "visa" from the db (this would happen lots of times for each card type):
cardtype_total_amount[cardtype][0] += 0.5;
cardtype_total_amount[cardtype][1] += 1.7;
//add more keys for other cardtypes, and update their totals as per above...
我認為您只是缺少初始化!
//initialize the dictionary but do not populate yet
Dictionary<string, List<decimal>> cardtype_total_amount = new Dictionary<string, List<decimal>>();
[編輯]哦,下面的小數點上需要一些m,否則它們是雙精度數:
cardtype_total_amount[cardtype][0] += 0.5m;
不確定這是否是您要的。 這個怎么樣?
Dictionary<string, List<decimal> array
= new Dictionary<string, List<decimal>>();
然后,對於每次讀入(由鍵和值組成),您都可以執行以下操作。
var addition = new { Key = "visa", Value = 3.14 };
array[addition.Key].Add(addition.Value);
請注意,我不在電腦旁,所以可以打錯字。 另外,它還取決於您如何接收后續值。 這里假設一次一次。 如果您獲得了它們的完整列表,則可以將其拆分為字典本身。
List<Piece> bunchOfValues = ...;
Dictionary<...> results = bunchOfValues.ToDictionary(key => key.NameOrType,
value => bunchOfValues.Where(...).Select(...));
最后,當您希望對所有內容進行匯總時,可以再次使用LINQ。
decimal sum = arrayOfValues.Sum(element => element);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.