如何转换KeyValuePair为Dictionary,因为ToDictionary在C#中不可用?
jwg*_*jwg 108
var dictionary = new Dictionary<string, object> { { kvp.Key, kvp.Value } };
Run Code Online (Sandbox Code Playgroud)
ToDictionary C#中确实存在(编辑:ToDictionary你想的不一样),可以像这样使用:
var list = new List<KeyValuePair<string, object>>{kvp};
var dictionary = list.ToDictionary(x => x.Key, x => x.Value);
Run Code Online (Sandbox Code Playgroud)
这list可能是一种List或其他IEnumerable任何东西.第一个lambda显示如何从列表项中提取键,第二个lambda显示如何提取值.在这种情况下,它们都是微不足道的.
如果我理解正确,则可以按照以下步骤进行操作:
new[] { keyValuePair }.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
Run Code Online (Sandbox Code Playgroud)
使用 System.Linq.Enumerable.ToDictionary() 扩展方法转换一个或多个 KeyValuePairs 的集合
Dictionary<string,string> result = new[] {
new KeyValuePair ("Key1", "Value1"),
new KeyValuePair ("Key2", "Value2")
}.ToDictionary(pair => pair.Key, pair => pair.Value);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
49610 次 |
| 最近记录: |