2015-11-02 60 views
1

我有一个字典,将从查询的结果填充。由于这个原因,我不知道什么数据值会在我初始化时进入字典(尽管显然我知道将使用什么数据类型)。我是C#的新手 - 我怎么设置它?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... 
+0

你知道**有关数据的任何事吗?例如,它会总是由一个字符串和两个浮点组成? –

+0

你是什么意思“失败”?它抛出异常吗? –

+0

@KonradViltersten是数据来自SQL Server,并且将始终是一个字符串和两个“钱”型变量。 – mulllhausen

回答

5

我认为你只是缺少一个initalisation !

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

这样做了。我实际上认为我通过声明它的类型来初始化字典。我猜不会。 – mulllhausen

3

不知道这是否是你追求的。这个怎么样?

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); 
+0

谢谢。非常有用的东西。 – mulllhausen