簡體   English   中英

轉換字典清單 <string, List> 進入列表C#Linq

[英]Convert List of Dictionary<string, List> into list C# Linq

這是我的源類型=> IEnumerable<IDictionary<string, IEnumerable<string>>>
這是我的目標類型=> IEnumerable<string>

預期產量

字符串清單

[
 "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]"
 ]

input
   .ToList()
   .SelectMany(d => d)
   .Select(i => $"ca:{i.Key}:{i.Value.Select(l => l)}")
   .ToList()

您正在尋找在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

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

如果有人可以提出一種干凈的方法來處理SelectMany的多種方法,而不是將它們堆疊在一起,那么我想了解一下自己的觀點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM