简体   繁体   English

字典 <something, List<> &gt;展平(取消分组)到列表中的某物和元素的列表-C#

[英]Dictionary<something, List<>> flatten (ungroup) to List of something and elements from List - C#

I want to flatten (ungroup) my dictionary - and trying if it can be done by Linq. 我想拼合(取消分组)我的字典-并尝试是否可以由Linq完成。

Sample input: 输入样例:

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"});

What i want to achieve is List of following elements: 我要实现的是以下元素列表:

0a 0a

0b 0b

1c 1c

1d 1天

of course it can be done with: 当然可以通过以下方式完成:

List<string> output = new List<string>();
foreach (var element in dict)
{
    foreach (var valuesElement in element.Value)
    {
        output.Add(element.Key + valuesElement);
    }
}

I'm only looking if there is any "clever" linq construction to achieve it. 我只是在寻找是否有任何“聪明的” linq构造来实现它。

Use SelectMany on the dictionary and the construct the items based on value in the key value pair 在字典上使用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(); 

You are looking for .SelectMany() 您正在寻找.SelectMany()

dict.SelectMany(x => x.Value.Select(y => $"{x.Key}{y}"));

Here's more explanation on how it works. 这是有关其工作原理更多说明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM