简体   繁体   中英

How to access value in a Dictionary that has a Tuple as the Key in c#?

I have created a dictionary with Tuples as keys and a enumerator as value.

mKeyValue.Add(Tuple.Create(lineCount,columnID),(E)style);

mKeyValue is the dictionary.

static Dictionary<Tuple<int,int>,E> mKeyValue = new Dictionary<Tuple<int,int>,E>();

Now how to access elements in this dictionary? I used something like this,

mKeyValue[Tuple<lineCount,columnID>];

but it doesn't work.

It's no different than usage with any other type of key. You need to pass an instance of the type, not the type (declaration) itself to the indexer.

You wouldn't say myKeyValue[int] , for a Dictionary<int, ...> , when you really wanted myKeyValue[5] . Just the the key looks a little more "complicated" in this case.

Example:

// Lookup entry for LineCount = 1, ColumnID = 4711
var value = myKeyValue[Tuple.Create(1, 4711)];

Basically, just like you did when adding an entry with Dictionary<>.Add(...) .

If you already have a Tuple<int,int> defined then use that as key like mKeyValue[t];

Tuple<int,int> t = Tuple.Create(1, 1);
mKeyValue.Add(Tuple.Create(1, 1), (E)21);
var data = mKeyValue[t];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM