Search code examples
c#stringdictionaryjoin.net-5

Apply string. join on Dictionary<string, List<int>>


I have situation where i have a dictionary of type Dictionary<string, List<int>> . I would like to apply sting.Join to it, I would like to have data displayed like:

"abc1:1,2,3,4,abc2:1,3,8,abc3:3,1,7" 

what i tried is this :

$"{string.Join(", ", iformation.OrderBy(x => x.Key).Select(x => x.Key + ": " + string.Join(",", x.Value.ToArray())))}";

The output was :

System.Collections.Generic.Dictionary`2+KeyCollection[System.String,System.Collections.Generic.List`1[System.Int32]]:

can somebody help me with what i want to achieve ?


Solution

  • Output like yours happens, when you invoke ToString method on collections (dictionary in your case). Below you can find correct code and compare to it:

    var dict = new Dictionary<string, List<int>>()
    {
        ["abc1"] = [1,2,3,4],
        ["abc3"] = [3,1,7],
        ["abc2"] = [1,3,8],
    };
    
    var result = string.Join(
        ", ", 
        dict
            .OrderBy(x => x.Key)
            .Select(x => $"{x.Key}:{string.Join(",", x.Value)}"));
    

    Here you can find working example.