Reputation: 213
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");
Upvotes: 0
Views: 191
Reputation: 134601
You can use LINQ to help you out there.
TypeID = measurementTypes.Where(kvp => kvp.Value == "GEN")
.Select(kvp => kvp.Key)
.FirstOrDefault()
Upvotes: 0
Reputation: 684
TypeID = measurementTypes.Values.Where(v => v.Equals("GEN")).FirstOrDefault();
Upvotes: 0
Reputation: 1503479
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.
Upvotes: 3