tags:

views:

54

answers:

2

Hi,

Weird question, but I have a dictionary created with StringComparer.OrdinalIgnoreCase, looks something like this

AaA, 10
aAB, 20
AAC, 12

I then use myDictionary["AAA"] to find the value associated with the key, but what I also need to know is what the actual spelling of the key is in myDictionary, e.g. in this case I want it to return AaA. Any way to do this without a loop? Thx.

+2  A: 
string value = myDictionary.First(v => StringComparer.Create(CultureInfo.CurrentCulture,true)
                  .Compare(v.Key,"AAA") == 0)
                  .Key
David Neale
The Dictionary is defined as Dictionary<string, int>so myDictionary["AAA"] returns an integer...
Andrew White
Ah, you're right. I've amended the answer above with an alternative solution (doesn't take advantage of the OrdinalIgnoreCase dictionary but could be easier if you're only pulling out the key once).
David Neale
I think this amended solution is still looping... the looping is just delegated to LINQ...
Cameron Peters
True, although the CLR will be optimised for this type of operation so I can't imagine there would be much difference in performance. I'll give it a try later...just for kicks!
David Neale
A: 

Change your dictionary so it looks like this:

public struct myValue
{
    int myInt;
    string MixedCaseWord;
}

var dictionary = new Dictionary<string, myValue>(StringComparer.OrdinalIgnoreCase);

var key = "AaA";
dictionary.Add(key, new MyValue { myInt = 10, MixedCaseWord = key }); 

var correctSpelling = dictionary["AAA"].MixedCaseWord;
Cameron Peters
Nice, thanks a lot.
Andrew White