![](/img/trans.png)
[英]c#: How to iterate through a List<>, that is a value in a dictionary?
[英]How to iterate through dictionary whose value field is list in c#?
我有需要在foreach循环中迭代的Dictionary<Key, IList<Days>> days
,因此我可以将其转换为Dictionary<Key, IList<string>> days2
; 我尝试使用以下方法,但编译器不喜欢它(无法转换为元素类型。
foreach(KeyValuePair<string,IList<Days>> kvp in days)
{
//do stuff
}
您如何遍历值是list的字典键值对? 如果可能的话,我试图避免使用linq使其更具可读性。
您可以使用隐式类型的局部变量,而不是精确地指定类型。 使用var
关键字完成:
foreach (var kvp in dict)
{
}
您还可以使用LINQ获得所需的Dictionary<Key, IList<string>>
:
Dictionary<Key, IList<string>> dict2 =
dict.ToDictionary(x => x.Key,
x => (IList<String>)x.Value.Select(y => y.ToString()).ToList());
将您要使用的简单ToString()
调用替换为Days
以进行string
转换。
您将字典定义为Dictionary<Key, IList<Days>>
,这意味着您应该在foreach循环中匹配这些类型:
foreach (KeyValuePair<Key, IList<Days>> kvp in days)
{
foreach (Days day in kvp.Value)
{
// Convert individual elements
}
}
您的另一个选择是使用ToDictionary
扩展方法进行转换:
days.ToDictionary(d => d.Key, d => Value.Select(d => d.ToString()));
foreach(KeyValuePair<string,IList<Days>> kvp in days)
{
IList<Days> dayList = kvp.Value;
// TODO: convert and insert in new dictionary
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.