Search code examples
c#listkey-value

How to convert list of key-value pairs to list of string (key,value)


I have a list of key-value pairs.

var y = this.Request.Cookies.ToList();

which would have multiple Key="Key",Value="value" pairs.

This has to be converted to a List of string => "key","Value" pairs.

Any suggestions?


Solution

  • Work with .Select() from System.Linq to convert Key-Value pair to string.

    using System.Linq;
    
    Dictionary<string, string> dict = new Dictionary<string, string>
    {
        { "Key1", "Value1" },
        { "Key2", "Value2" },
        { "Key3", "Value3" }
    };
            
    List<string> result = dict
        .Select(x => $"{x.Key},{x.Value}")
        .ToList();
    

    Sample program