0

I have an IDictionary (no not a IDictionary<TKey, TValue>) and want to get the keys and values from it.

In the end I would like to have keys and values as a string like key1=value1;key2=value2;... but at first I need to cast those pairs correctly.

I already tried a few solutions like IDictionary to string, but none of them worked for a IDictionary.

The dictionary I'm trying to read is the Exception.Data dictionary.

dymanoid
  • 14,771
  • 4
  • 36
  • 64
Hille
  • 2,123
  • 22
  • 39

2 Answers2

2

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

This should do the job

StringBuilder sb = new StringBuilder();

foreach (DictionaryEntry entry in (IDictionary)dictionary)
{
    sb.Append($"{entry.Key}={entry.Value};");
}

return sb.ToString();
Innat3
  • 3,561
  • 2
  • 11
  • 29