-2

I need a compound key (two strings) as my lookup value for a dictionary. I was thinking I could use a Tuple<string,string> for this, but as I understand it, the dictionary would perform a reference equality check, and I'd never get a match.

What can I do so that it will perform an actual string comparison?

Here's what I've got:

protected Dictionary<Tuple<string, string>, WopiSession> _sessions;

...

var sessionKey = new Tuple<string, string>(accessToken, fileToken);
WopiSession session;

if (!_sessions.TryGetValue(sessionKey, out session))
{
    session = new WopiSession();
    _sessions.Add(sessionKey, session);
}
mpen
  • 272,448
  • 266
  • 850
  • 1,236
  • Why didn’t you just try it out? – poke Oct 10 '14 at 16:50
  • @poke I'm going to....it's a complex program. It'll be another hour or so before I'm able to test it. I knew someone here would have the answer off the top of their head though, so why not ask before going down the wrong path? – mpen Oct 10 '14 at 16:52
  • 1
    possible duplicate of [Tuples( or arrays ) as Dictionary keys in C#](http://stackoverflow.com/questions/955982/tuples-or-arrays-as-dictionary-keys-in-c-sharp) – poke Oct 10 '14 at 16:53
  • also possible duplicate of [Composite Key Dictionary](http://stackoverflow.com/questions/2877660/composite-key-dictionary) – poke Oct 10 '14 at 16:54
  • 1
    Yeah and so you didn't even bothered to search for a duplicate question here. – Rahul Oct 10 '14 at 16:55
  • @Rahul If you must know I did perform a search on tuple equality which mentioned it performing reference equality, after which I assumed it wouldn't work with a dictionary. Didn't realize that only applied to `==` and not `.Equals`, which Dictionary uses. Anyway, if you've got a problem with this, close it as a dupe. – mpen Oct 10 '14 at 17:39
  • 1
    No offense but I have already done that. – Rahul Oct 10 '14 at 17:42
  • @Rahul I'm not offended. That's what you're supposed to do if there's a dupe. What you're not supposed to do is berate me for overlooking it. – mpen Oct 10 '14 at 17:53
  • 1
    `berate me for overlooking it` .. Oh! No .. don't get me wrong from my comment. That comment just meant to say .. "You mostly have didn't searched properly" and not to make you feel bad. No bad feelings .. Peace brother. – Rahul Oct 11 '14 at 08:55

1 Answers1

2

You don't need to do anything. Tuple override the default equality semantics of object to instead create a composite hash of the hashes of all of the objects it represents, and its Equals method compares each of the composed items for equality. Since strings also override equality based on the semantics of string equality, your code will work as is.

Servy
  • 202,030
  • 26
  • 332
  • 449