REading dictionary key value using linq code example
Example 1: linq get a dictionary key and value c#
var values = dictionary.Where(x => someKeys.Contains(x.Key)).Select(x => x.Value);
var keys = dictionary.Where(x => someValues.Contains(x.Value)).Select(x => x.Key);
Example 2: reading dictionary key value using linq and storig into a variable
public static class DictionaryHelper
{
public static IDictionary<string, double> LossPercentageDic()
{
var dictionaryLossPercentage = new Dictionary<string, double>();
dictionaryLossPercentage.Add("Less than 10%", 0.05);
dictionaryLossPercentage.Add("10% to 24%", 0.15);
dictionaryLossPercentage.Add("25% to 49%", 0.4);
dictionaryLossPercentage.Add("50% to 74%", 0.66);
dictionaryLossPercentage.Add("75% and more", 1);
return dictionaryLossPercentage;
}
}
var howMuchAffectedMainString = aHousehold.HowMuchAffectedMain != null ?
DictionaryHelper.LossPercentageDic()
.Where(kvp => kvp.Value == (double)aHousehold.HowMuchAffectedMain)
.Select(x => new { Key = x.Key }).ToList().FirstOrDefault().Key : "";
HowMuchAffectedMain = aHousehold.HowMuchAffectedMain != null ?
DictionaryHelper.LossPercentageDic().Where(kvp => kvp.Value ==
(double)aHousehold.HowMuchAffectedMain)
.Select(x => new { Key = x.Key }).ToList().FirstOrDefault().Key : "",