[英]Dictionary as a Lookup value
To have a holiday calculation I have to load holidays from repository for a year and for multiple countries and their state. 为了计算假期,我必须从存储库中加载一年以及多个国家/地区及其州的假期。
To get good performance in a logic where I need to check if a date is holiday or not, I am trying to convert a list to lookup using .ToLookup extension with a dictionary as a value of it. 为了在需要检查日期是否为节假日的逻辑中获得良好的性能,我尝试使用.ToLookup扩展名(其值为字典)将列表转换为查找。
This Dictionary will have State as a key and HashSet for that state as a value. 该词典将以状态作为键,并以该状态的HashSet作为值。
I am trying to create it using Lookup, Dictionary and HashSet, so that I can quickly reach to holiday info by filtering it using Country and State. 我正在尝试使用Lookup,Dictionary和HashSet创建它,以便可以通过使用Country和State对其进行过滤来快速获取假日信息。
following is the code: 以下是代码:
var CountryStateHolidayLookup = holidays.ToLookup(x => x.Country,
x => (
new Dictionary<int, HashSet<Holiday>>()
{ { x.State,
new HashSet<Holiday>()
{ new Holiday(
x.HolidayDate.Date, x.IsWeekend)
}
} }
)
);
in the output of above code I get a Lookup with country code , value of this lookup is coming an enumerable of Dictionary with each holiday as a new dictionary. 在上面代码的输出中,我得到了一个包含国家代码的查找,该查找的值即将成为一个枚举的Dictionary,每个假期都将其作为新词典。
whereas I was expecting a dictionary with all item as one HashSet 而我期待一本将所有项作为一个HashSet的字典
I know I am doing something wrong here , What changes I have to do ? 我知道我在这里做错了什么,我必须做些什么改变?
I think you have it backwards. 我认为你倒退了。 A lookup can be thought of as a multi-valued dictionary. 查找可以看作是多值字典。 You'll want country key in to the lookup of states. 您将需要国家(地区)键入状态查询。
You probably want something like this: 您可能想要这样的东西:
var CountryStateHolidayLookup = holidays.GroupBy(h => h.Country)
.ToDictionary(
g => g.Key,
g => g.ToLookup(
h => h.State,
h => new Holiday(h.HolidayDate.Date, h.IsWeekend)
)
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.