C# 将字典的列表转换为列表C Linq

C# 将字典的列表转换为列表C Linq,c#,linq,C#,Linq,这是我的源代码类型=>IEnumerable 这是我的目标类型=>IEnumerable 预期产量 字符串列表 [ "ca:aws_client:firstElementIntheList]", "ca:aws_client:secondElementInTheList]" ] [ "ca:aws_client:System.Linq.Enumerable+SelectListIterator`2[System.String,System.String]", "ca:aws_clien

这是我的源代码类型=>IEnumerable 这是我的目标类型=>IEnumerable

预期产量 字符串列表

[ "ca:aws_client:firstElementIntheList]", "ca:aws_client:secondElementInTheList]" ] [ "ca:aws_client:System.Linq.Enumerable+SelectListIterator`2[System.String,System.String]", "ca:aws_client:System.Linq.Enumerable+SelectListIterator`2[System.String,System.String]" ]
您希望在SelectMany中使用结果选择器,而不是第二个select语句

这样的东西可能就是你想要的:

var dict = new Dictionary<string, IEnumerable<string>> 
{
    {"one", new List<string> {"1","2","3"}},
    {"two", new List<string> {"1","2","3"}}
};

var res = dict.SelectMany(d => d.Value, (a, b) => $"ca:{a.Key}:{b}");

foreach(var val in res)
    Console.WriteLine(val);

/* output:

ca:one:1
ca:one:2
ca:one:3
ca:two:1
ca:two:2
ca:two:3
*/

如果有人能提出一种干净的方法来处理多方法语法SelectMany,而不是将它们堆叠起来,我想了解一下,以供我自己参考。

您希望在SelectMany中使用一个结果选择器,而不是第二个select语句

这样的东西可能就是你想要的:

var dict = new Dictionary<string, IEnumerable<string>> 
{
    {"one", new List<string> {"1","2","3"}},
    {"two", new List<string> {"1","2","3"}}
};

var res = dict.SelectMany(d => d.Value, (a, b) => $"ca:{a.Key}:{b}");

foreach(var val in res)
    Console.WriteLine(val);

/* output:

ca:one:1
ca:one:2
ca:one:3
ca:two:1
ca:two:2
ca:two:3
*/

如果有人能提出一种干净的方法来处理多方法语法,而不是堆叠它们,我想知道这对我自己有什么启发。

我明白了。这真的很酷。非常感谢你。但我不知道这是怎么回事。你能详细说明一下吗。Thanks@MuthaiahPL我稍后会详细介绍。我发现SelectMany的方法语法比查询语法更令人困惑。以字典为例,这更有意义吗?var res=dict中的from kvp from kvp中的val.Value选择$ca:{kvp.Key}:{val};var res=list.SelectManydict=>dict.SelectManykvp=>kvp.Value.Selectval=>$ca:{kvp.Key}:{val};我明白了。这真的很酷。非常感谢你。但我不知道这是怎么回事。你能详细说明一下吗。Thanks@MuthaiahPL我稍后会详细介绍。我发现SelectMany的方法语法比查询语法更令人困惑。以字典为例,这更有意义吗?var res=dict中的from kvp from kvp中的val.Value选择$ca:{kvp.Key}:{val};var res=list.SelectManydict=>dict.SelectManykvp=>kvp.Value.Selectval=>$ca:{kvp.Key}:{val};
var list = new List<Dictionary<string, IEnumerable<string>>> 
    {
    new Dictionary<string, IEnumerable<string>> {
        {"one", new List<string> {"1","2","3"}},
        {"two", new List<string> {"1","2","3"}}
    },
    new Dictionary<string, IEnumerable<string>> {
        {"three", new List<string> {"1","2","3"}},
        {"four", new List<string> {"1","2","3"}}
    }
};


var res = list.SelectMany(x => x)
              .SelectMany(d => d.Value, (a, b) => $"ca:{a.Key}:{b}");

foreach(var val in res)
    Console.WriteLine(val);