Muthaiah PL
Muthaiah PL

Reputation: 1158

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

This is my source type => IEnumerable<IDictionary<string, IEnumerable<string>>>
This is my target type => IEnumerable<string>

Expected Output

List of strings

 [
 "ca:aws_client:firstElementIntheList]",
 "ca:aws_client:secondElementInTheList]"
 ]

Actual Output

List of strings

 [
 "ca:aws_client:System.Linq.Enumerable+SelectListIterator`2[System.String,System.String]",
 "ca:aws_client:System.Linq.Enumerable+SelectListIterator`2[System.String,System.String]"
 ]

Code

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

Upvotes: 0

Views: 373

Answers (1)

Jonathon Chase
Jonathon Chase

Reputation: 9714

You're looking to use a result selector in SelectMany instead of a second select statement.

Something like this may be what you want:

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
*/

Edit:

I've noticed you're actually using a List of Dictionaries. The solution is largely the same, but with more 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);

If someone can suggest a clean way to handle the multiple method syntax SelectMany other than stacking them, I'd like to know for my own edification.

Upvotes: 2

Related Questions