86

I want to keep some totals for different accounts. In C++ I'd use STL like this:

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;

Now, how would I do the same thing in C# ?

1
  • 1
    C# Dictionary is equivalent to C++ unordered_map. Furthermore, C# SortedDictionary is equivalent to C++ map. Oct 11, 2022 at 18:43

8 Answers 8

113

Roughly:-

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"]);
9
  • 1
    Perhaps I should clarify that comment by saying "I do not know the names, or how many names I will have". In this answer, if I added accounts["Ron"] += 2.50;, it would throw an exception. In reality, I'll be throwing an XML file at it with lots of names and numbers. Oct 21, 2009 at 0:46
  • 4
    Actually no, if you use the index and attempt to set a non-existent key, it will actually create the object for you with the specified key. An exception will only be thrown on the get operation. Look here on remarks: msdn.microsoft.com/en-us/library/9tee9ht2.aspx Oct 21, 2009 at 1:06
  • 1
    @Alex: because var is much shorter than IParallelEnumerable<Record<string,XmlSerializer>> :) Dec 6, 2013 at 12:18
  • 7
    Dictionaries in c# are not equivalent to stl::map's just so you know - c# dictionaries are hash tables whereas stl::map's are red-black trees, the underlying algorithms are totally different. Apr 23, 2014 at 21:19
  • 3
    Note, that the accounts["Fred"] = 0;in this example is equivalent to accounts.Add("Fred", 0); (See dotnetfiddle.net/q3UteL for both variants) Also: *When you use Dictionary.Add( Key, Value ) to add a new KeyValuePair an ArgumentException will be thrown if the Key already exists in the dictionary. *Using the indexer (Dictionary[ Key ]) you get an implicit add-or-update behavior since the Key will automatically be added if it is not contained in the Dictionary already otherwise the corresponding value will simply be updated. *Consider using decimal for currency Oct 7, 2015 at 6:51
20
Dictionary<string, double> accounts;
0
17

Although System.Collections.Generic.Dictionary matches the tag "hashmap" and will work well in your example, it is not an exact equivalent of C++'s std::map - std::map is an ordered collection.

If ordering is important you should use SortedDictionary.

6

You want the Dictionary class.

0
2

Dictionary is the most common, but you can use other types of collections, e.g. System.Collections.Generic.SynchronizedKeyedCollection, System.Collections.Hashtable, or any KeyValuePair collection

1
  • Is it true that C# Dictionary is equivalent to C++ unordered_map ? If yes, then the question is: What is the C# equivalence of C++ map ? Oct 11, 2022 at 18:38
2

This code is all you need:

   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);
        }
    }

And the content is:

Name: Fred; Amount: R$ 8,20;
Name: John; Amount: R$ 10,00;

That is the way of doing this in C# - in a declarative way!

I hope this helps,

Ricardo Lacerda Castelo Branco

1
  • Well, I've already done it with Dictionary now but the XML is real simple, just a list of tags like this: <transaction name="Fred" amount="5.20" /> Oct 21, 2009 at 0:57
1

While we are talking about STL, maps and dictionary, I'd recommend taking a look at the C5 library. It offers several types of dictionaries and maps that I've frequently found useful (along with many other interesting and useful data structures).

If you are a C++ programmer moving to C# as I did, you'll find this library a great resource (and a data structure for this dictionary).

-Paul

1

The closest equivalent of C++ std::map<> (a tree internally) is C# OrderedDictionary<> (a tree internally), while C# OrderedDictionary<> is missing some very important methods from C++ std::map<>, namely: std::map::find, std::map::lower_bound, std::map::upper_bound, std::map::equal_range, and std::map iterators, which are basically the backbone for the previous 4 methods.

Why those 4 methods are important? Because it gives us the ability to locate the "whereabouts" of a given key, in addition to only being able to check if a key exists, or the SortedDictionary is guaranteed to be ordered.

What is "whereabouts" of a key in a std::map? The key doesn't necessarily have to exist in the collection, we want to know the location the key might be at, usually between two iterators pointing to two adjacent existing keys respectively in the collection, so we can operate on the range the key falls into in a O(logN) complexity. Without such 4 methods (with iterators), one has to do an O(N) iteration through the collection every time a range is queried against a key.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.