IDictionary上的LINQ操作
本文关键字:操作 LINQ 上的 IDictionary | 更新日期: 2023-09-27 18:02:02
假设我有以下字典:
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语句。
你可以试试这个,不过没有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;
}
或者一个Linq:
return iDic.Keys.Cast<object>().ToDictionary(k=> k.ToString(), v=> iDic[v]);
诀窍是将IDictionary转换为DictionaryEntry的泛型类型。然后可以使用System.Linq.中的ToDictionary((
static Dictionary<string,object> ToDictionary(IDictionary dic)
{
return dic.Cast<DictionaryEntry> ().ToDictionary ((t) => t.Key.ToString (), (t) => t.Value);
}
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);
}
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);
https://dotnetfiddle.net/eY41MQ