[英]Dictionary<something, List<>> flatten (ungroup) to List of something and elements from List - C#
我想拼合(取消分组)我的字典-并尝试是否可以由Linq完成。
输入样例:
Dictionary<int, List<string>> dict = new Dictionary<int, System.Collections.Generic.List<string>>();
dict.Add(0, new List<string>() { "a", "b" });
dict.Add(1, new List<string>() { "c", "d"});
我要实现的是以下元素列表:
0a
0b
1c
1天
当然可以通过以下方式完成:
List<string> output = new List<string>();
foreach (var element in dict)
{
foreach (var valuesElement in element.Value)
{
output.Add(element.Key + valuesElement);
}
}
我只是在寻找是否有任何“聪明的” linq构造来实现它。
在字典上使用SelectMany
并根据键值对中的值构造项目
Dictionary<int, List<string>> dict = new Dictionary<int, System.Collections.Generic.List<string>>();
dict.Add(0, new List<string>() { "a", "b" });
dict.Add(1, new List<string>() { "c", "d" });
List<string> output = dict.SelectMany(kvp => kvp.Value.Select(v => string.Format("{0}{1}", kvp.Key, v))).ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.