[英]C# equivalent of C++ map<string,double>
我想為不同的帳戶保留一些總計。 在C ++中我會像這樣使用STL:
map<string,double> accounts;
// Add some amounts to some accounts.
accounts["Fred"] += 4.56;
accounts["George"] += 1.00;
accounts["Fred"] += 1.00;
cout << "Fred owes me $" << accounts['Fred'] << endl;
現在,我將如何在C#中做同樣的事情?
大致:-
var accounts = new Dictionary<string, double>();
// Initialise to zero...
accounts["Fred"] = 0;
accounts["George"] = 0;
accounts["Fred"] = 0;
// Add cash.
accounts["Fred"] += 4.56;
accounts["George"] += 1.00;
accounts["Fred"] += 1.00;
Console.WriteLine("Fred owes me ${0}", accounts["Fred"]);
Dictionary<string, double> accounts;
盡管System.Collections.Generic.Dictionary匹配標記“hashmap”並且在您的示例中運行良好,但它並不完全等同於C ++的std :: map - std :: map是一個有序集合。
如果排序很重要,您應該使用SortedDictionary 。
你想要Dictionary類。
字典是最常見的,但您可以使用其他類型的集合,例如System.Collections.Generic.SynchronizedKeyedCollection,System.Collections.Hashtable或任何KeyValuePair集合
這段代碼就是您所需要的:
static void Main(string[] args) {
String xml = @"
<transactions>
<transaction name=""Fred"" amount=""5,20"" />
<transaction name=""John"" amount=""10,00"" />
<transaction name=""Fred"" amount=""3,00"" />
</transactions>";
XDocument xmlDocument = XDocument.Parse(xml);
var query = from x in xmlDocument.Descendants("transaction")
group x by x.Attribute("name").Value into g
select new { Name = g.Key, Amount = g.Sum(t => Decimal.Parse(t.Attribute("amount").Value)) };
foreach (var item in query) {
Console.WriteLine("Name: {0}; Amount: {1:C};", item.Name, item.Amount);
}
}
內容如下:
姓名:弗雷德; 金額:8,20雷亞爾;
姓名:約翰; 金額:R $ 10,00;
這是在C#中以聲明方式執行此操作的方式!
我希望這有幫助,
Ricardo Lacerda Castelo Branco
當我們談論STL,地圖和字典時,我建議你看一下C5庫。 它提供了我經常發現有用的幾種類型的詞典和地圖(以及許多其他有趣和有用的數據結構)。
如果你是一個像我一樣轉向C#的C ++程序員,你會發現這個庫是一個很好的資源(以及這個字典的數據結構)。
- 保羅
最接近的C ++ std::map<>
(內部樹)是C# OrderedDictionary<>
(內部的一個樹),而C# OrderedDictionary<>
缺少一些來自C ++ std::map<>
非常重要的方法,即: std::map::find
, std::map::lower_bound
, std::map::upper_bound
, std::map::equal_range
和std::map
iterators
,它們基本上是前4種方法的主干。
為什么這4種方法很重要? 因為它使我們能夠定位給定鍵的“行蹤”,除了只能檢查是否存在鍵,或者保證SortedDictionary被訂購。
什么是std::map
鍵的“行蹤”? 密鑰不一定必須存在於集合中,我們想要知道密鑰可能位於的位置,通常在兩個迭代器之間,分別指向集合中的兩個相鄰的現有密鑰,因此我們可以在密鑰落下的范圍內操作進入O(logN)
復雜性。 如果沒有這樣的4種方法(使用迭代器),每次針對密鑰查詢范圍時,都必須通過集合進行O(N)
迭代。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.