假设我有以下词典:
private Dictionary<int, string> dic1 = new Dictionary<int, string>()
{
{ 1, "a" },
{ 2, "b" },
{ 3, "c" }
}
private Dictionary<SomeEnum, bool> dic2 = new Dictionary<SomeEnum, bool>()
{
{ SomeEnum.First, true },
{ SomeEnum.Second, false },
{ SomeEnum.Third, false }
}
我想将这两个词典转换为Dictionary<string, object>
例如:
dic1 = new Dictionary<string, object>()
{
{ "1", "a" },
{ "2", "b" },
{ "3", "c" }
}
dic2 = new Dictionary<string, object>()
{
{ "First", true },
{ "Second", false },
{ "Third", false }
}
正如您所看到的,这些词典的string
键只是之前词典的string
表示。
负责转换的方法具有以下签名:
public static object MapToValidType(Type type, object value)
{
//....
if(typeof(IDictionary).IsAssignableFrom(type))
{
//I have to return a Dictionary<string, object> here
return ??;
}
}
我尝试了以下内容:
((IDictionary)value).Cast<object>().ToDictionary(i => ...);
但是i
被转换为一个对象,所以我无法访问键或值项。为此,我需要将其投放到合适的KeyValuePair<TKey, TValue>
,但我不知道TKey
或TValue
类型。
另一种解决方案是:
IDictionary dic = (IDictionary)value;
IList<string> keys = dic.Keys.Cast<object>().Select(k => Convert.ToString(k)).ToList();
IList<object> values = dic.Values.Cast<object>().ToList();
Dictionary<string, object> newDic = new Dictionary<string, object>();
for(int i = 0; i < keys.Count; i++)
newDic.Add(keys[0], values[0]);
return newDic;
但是,我并不喜欢这种方法,我真的在寻找一个更简单,更友好的单行LINQ语句。
答案 0 :(得分:1)
static void Main(string[] args)
{
var blah = KeyToString(dic1);
// Verify that we converted correctly
foreach (var kvp in blah)
{
Console.WriteLine("{0} {1}, {2} {3}", kvp.Key.GetType(), kvp.Key, kvp.Value.GetType(), kvp.Value);
}
}
static Dictionary<string, TValue> KeyToString<TKey, TValue>(IEnumerable<KeyValuePair<TKey, TValue>> dic1)
{
return dic1.ToDictionary(kvp => kvp.Key.ToString(), kvp => kvp.Value);
}
答案 1 :(得分:1)
你可以试试这个,不过LINQ,我觉得你不需要:
x.h
或者是Linq:
Dictionary<string, object> ConvertToDictionary(System.Collections.IDictionary iDic) {
var dic = new Dictionary<string, object>();
var enumerator = iDic.GetEnumerator();
while (enumerator.MoveNext()) {
dic[enumerator.Key.ToString()] = enumerator.Value;
}
return dic;
}
答案 2 :(得分:0)
public static IDictionary<string, object> Convert<TKey, TValue>(IDictionary<TKey, TValue> genDictionary)
{
return genDictionary.Select(kvp => new KeyValuePair<string, object>(kvp.Key.ToString(), (object)kvp.Value)).ToDictionary(x => x.Key, x => x.Value);
}
调用如:
var dicIntInt = new Dictionary<int, string>{{123, "asdc"}, {456, "aa"} };
Dictionary<string, object> dicStrObj = Convert(dicIntInt);
答案 3 :(得分:-1)
诀窍是将您的IDictionary转换为通用类型的DictionaryEntry。然后,您可以使用System.Linq中的ToDictionary()。
static Dictionary<string,object> ToDictionary(IDictionary dic)
{
return dic.Cast<DictionaryEntry> ().ToDictionary ((t) => t.Key.ToString (), (t) => t.Value);
}