相当于C ++的C#映射<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; 

尽pipeSystem.Collections.Generic.Dictionary与标签“hashmap”相匹配,并能在你的例子中很好地工作,但它不是C ++的std :: map的完全等价物 – std :: map是一个有序的集合。

如果sorting很重要,你应该使用SortedDictionary 。

你想要Dictionary类。

字典是最常见的,但您可以使用其他types的集合,例如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雷亚尔;
名字:约翰; 金额:10万雷亚尔;

这是在C#中这样做的方式 – 以声明的方式!

我希望这有帮助,

Ricardo Lacerda Castelo Branco

当我们谈论STL,地图和词典时,我build议看看C5库。 它提供了几种types的字典和地图,我经常发现有用的(以及许多其他有趣和有用的数据结构)。

如果你是一个C ++程序员,像我一样移动到C#,你会发现这个库是一个很好的资源(和这个字典的数据结构)。

– 保罗

C ++ std::map<> (树内部)的最接近的等价物是C# OrderedDictionary<> (内部树),而C# OrderedDictionary<>缺less一些非常重要的方法从C ++ std::map<> ,即: std::map::findstd::map::lower_boundstd::map::upper_boundstd::map::equal_rangestd::map iterators ,它们基本上是前面4种方法的基础。

为什么这4种方法很重要? 因为它使我们能够定位给定键的“行踪”,除了能够检查键是否存在,或者SortedDictionary是有序的。

什么是std::map的一个键的“whereabouts”? 密钥不一定必须存在于集合中,我们希望知道密钥可能位于的位置,通常在两个迭代器之间分别指向集合中相邻的两个现有密钥,所以我们可以在密钥的范围内进行操作成O(logN)复杂度。 如果没有这样的4个方法(使用迭代器),每次使用键来查询范围时,都必须通过集合进行O(N)迭代。