从IDictionary获取所有条目

我有一个IDictionary(不是IDictionary<TKey,tvalue>),想从中获取键和值。

最后,我希望将键和值作为字符串,例如key1=value1;key2=value2;...,但首先我需要正确地转换那些对。

我已经尝试了IDictionary to string之类的一些解决方案,但没有一个适用于IDictionary

我要阅读的字典是Exception.Data字典。

c2125102 回答:从IDictionary获取所有条目

在IDictionary实例上使用foreach循环创建所需的字符串

IDictionary具有“键和值”属性,但是您可以使用GetEnumerator返回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);
  }
}

测试

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

输出

a=1;b=2;c=3

如果需要解析大型集合,可以使用StringBuilder

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

如果要获取键和值的列表

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

这应该可以完成

StringBuilder sb = new StringBuilder();

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

return sb.ToString();
本文链接:https://www.f2er.com/3139232.html

大家都在问