Mat*_*ero 7 c# linq dictionary
假设我有以下词典:
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 }
}
Run Code Online (Sandbox Code Playgroud)
我想将这两个词典转换成一个 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 }
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,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 ??;
}
}
Run Code Online (Sandbox Code Playgroud)
我尝试过以下方法:
((IDictionary)value).Cast<object>().ToDictionary(i => ...);
Run Code Online (Sandbox Code Playgroud)
但是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;
Run Code Online (Sandbox Code Playgroud)
但是,我并不喜欢这种方法,我真的在寻找一个更简单,更友好的单行LINQ语句.
你可以试试这个,虽然没有 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;
}
Run Code Online (Sandbox Code Playgroud)
或 Linq 之一:
return iDic.Keys.Cast<object>().ToDictionary(k=> k.ToString(), v=> iDic[v]);
Run Code Online (Sandbox Code Playgroud)