tags:

views:

56

answers:

3

I need to use a list pulled from sql, list is built from

 Dictionary<Int32, String> measurementTypes = this.GetIndicatorTypes(MeasurementTypeFilter.All);

is ther a way to retrive the key using the string. Something like

TypeID = measurementTypes.contains("GEN");
+3  A: 

Well, it'll be slow (i.e. O(n)), but you can do:

var keys = measurementTypes.Where(pair => pair.Value == "GEN")
                           .Select(pair => pair.Key);

That will give you a sequence of pairs which have the given value. There could be 0, 1 or many matches. From there you can pick the first matching key etc - whatever you need. Using First or Single would be appropriate if you think there will be at least one or exactly one; FirstOrDefault would return 0 if there were no matches, which may not be appropriate for you if 0 could also be a valid key.

Jon Skeet
@Jon: Wouldn't there be a way to use `DefaultIfEmpty` to mimic the functionality of `FirstOrDefault`, except with the ability to specify the default value?
Steven Sudit
Yeah, this is probably the best approach. I went ahead and deleted my answer as doing `First` or `FirstOrDefault` would not be failsafe.
Brian Gideon
Something like `var key = measurementTypes.Where(pair => pair.value == "GEN").DefaultIfEmpty(ImpossibleValue).First().Key;`
Steven Sudit
@Steven: I think I'd prefer to convert it to an `int?` sequence, to be honest. That's a more appropriate representation, IMO.
Jon Skeet
@Jon: I can't argue with that, since we can use `null` instead of arbitrarily declaring some value to be invalid. What would the code for that look like?
Steven Sudit
Let me answer my own question: `var key = measurementTypes.Where(pair => pair.Value == "Bye").Select( pair => (int?)pair.Key).FirstOrDefault();`
Steven Sudit
@Steven: Yup, that's it.
Jon Skeet
A: 
TypeID = measurementTypes.Values.Where(v => v.Equals("GEN")).FirstOrDefault();
Flesrouy
Does this return an index?
Steven Sudit
No. This should return the actual value.
Flesrouy
Right, but he wants the key, not the value.
Steven Sudit
Oh. Well, I guess I read the question wrong then. :)
Flesrouy
Yeah, but not everyone is a robot. Jon Skeet is still a prototype; it's the next version that will take over the Earth.
Steven Sudit
A: 

You can use LINQ to help you out there.

TypeID = measurementTypes.Where(kvp => kvp.Value == "GEN")
                         .Select(kvp => kvp.Key)
                         .FirstOrDefault()
Jeff M