0

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()
0

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I got that. This is really cool. Thank you so much. But I didn't get how this Select Many works. Can you please elaborate a bit. Thanks
@MuthaiahPL I'll try to expand on it later. I find the method syntax for SelectMany to be much more confusing than the query syntax. For the dictionary example, does this make more sense? var res = from kvp in dict from val in kvp.Value select $"ca:{kvp.Key}:{val}";
var res = list.SelectMany(dict => dict).SelectMany(kvp => kvp.Value.Select(val => $"ca:{kvp.Key}:{val}"));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.