开发者

Need to look up key using string in a Dictionary<TKey, TValue> Class

开发者 https://www.devze.com 2023-01-07 13:10 出处:网络
I need to use a li开发者_如何学编程st pulled from sql, list is built from Dictionary<Int32, String> measurementTypes = this.GetIndicatorTypes(MeasurementTypeFilter.All);

I need to use a li开发者_如何学编程st 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");


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.


TypeID = measurementTypes.Values.Where(v => v.Equals("GEN")).FirstOrDefault();


You can use LINQ to help you out there.

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号