Using a foreach loop on IDictionary instance to create the expected string
IDictionary has Keys and Values properties but you can achieve your goal like with this extension method using the GetEnumerator
that returns a DictionaryEntry
:
using System.Collections;
static public class IDictionaryHelper
{
static public string ToStringFormatted(this IDictionary dictionary,
char separator = ';')
{
string result = "";
foreach (DictionaryEntry item in dictionary)
result += $"{item.Key.ToString()}={item.Value.ToString()}{separator}";
return result.TrimEnd(separator);
}
}
Test
using System.Collections.Generic;
IDictionary myDictionary = new Dictionary<string, int>();
myDictionary.Add("a", 1);
myDictionary.Add("b", 2);
myDictionary.Add("c", 3);
Console.WriteLine(myDictionary.ToStringFormatted());
Fiddle Snippet
Output
a=1;b=2;c=3
You can use a StringBuilder if you need to parse large collections
using System.Collections;
using System.Text;
static public string ToStringFormatted(this IDictionary dictionary, char separator = ';')
{
var builder = new StringBuilder();
foreach ( DictionaryEntry item in dictionary )
builder.Append($"{item.Key.ToString()}={item.Value.ToString()}{separator}");
return builder.ToString().TrimEnd(separator);
}
If you want to get lists of keys and values
var keys = dictionary.Keys;
var values = dictionary.Values;
var listKeys = new List<object>();
var listValues = new List<object>();
foreach ( var item in keys )
listKeys.Add(item);
foreach ( var item in values )
listValues.Add(item);