C# 将字典转换为另一个具有不同键类型的字典
鉴于: 是否有一种简洁的LINQ转换方法:C# 将字典转换为另一个具有不同键类型的字典,c#,.net,linq,C#,.net,Linq,鉴于: 是否有一种简洁的LINQ转换方法: IDictionary==>IDictionary 以下要点: 类型KeyType1的2个值映射到相同的KeyType2 编辑查找可能返回空值,即映射可能不完整。在这种情况下,这些条目应该从新词典中删除 为了避免需要两次查找,您可以首先创建一个字典,将旧键映射到新键: class KeyType1{...} class KeyType2{...} class ValueType{...} public KeyType2 Lookup(KeyType
IDictionary
==>IDictionary
以下要点:
- 类型
的2个值映射到相同的KeyType1
KeyType2
- 编辑查找可能返回空值,即映射可能不完整。在这种情况下,这些条目应该从新词典中删除
查找
,您可以首先创建一个字典
,将旧键映射到新键:
class KeyType1{...}
class KeyType2{...}
class ValueType{...}
public KeyType2 Lookup(KeyType1 value)
{
// Returns a unique value of KeyType2 or otherwise, null
}
Dictionary StringDict=new Dictionary();
Dictionary IntDict=新字典();
StringDict.ToList().ForEach(D=>
{
IntDict.Add(转换为32(D.Key),D.Value);
});
您可以使用Where
首先过滤源代码,然后使用ToDictionary
扩展名指定新键和值:
Dictionary<string, string> StringDict = new Dictionary<string, string>();
Dictionary<int, string> IntDict = new Dictionary<int, string>();
StringDict.ToList().ForEach(D =>
{
IntDict.Add(Convert.ToInt32(D.Key), D.Value);
});
好的,假设
Lookup
是一个返回可能为null的引用类型的函数
dictionary1.ToDictionary(kv => Lookup(kv.Key) ?? ComputeNewKey(kv.Key),
kv => kv.Value);
注意编辑:
Lookup
可能会返回null更新后的我的答案。在人们已经回答了需求之后,更改需求有点棘手。我只是偶然读到了这个新问题(null返回查找)。如果发生了进一步的变化,请给我留下一条评论:)是的,我刚刚添加了它,我正在等待人们是否注意到而不是在3个答案上发表相同的评论(他们都给出得很快)是Lookup
一个ILookup
或IDictionary
?@JodrellLookup
是一种方法,如果不清楚,很抱歉(为了便于阅读,请随意编辑)
Dictionary<string, string> StringDict = new Dictionary<string, string>();
Dictionary<int, string> IntDict = new Dictionary<int, string>();
StringDict.ToList().ForEach(D =>
{
IntDict.Add(Convert.ToInt32(D.Key), D.Value);
});
var dictionary1 = new Dictionary<KeyType1, ValueType>();
var dictionary2 = dictionary1.Where(kv => Lookup(kv.Key) != null)
.ToDictionary(kv => Lookup(kv.Key), kv => kv.Value);
dictionary1.ToDictionary(kv => Lookup(kv.Key) ?? ComputeNewKey(kv.Key),
kv => kv.Value);
b = a
.Select(p => new { Key = Lookup(p.Key), p.Value }))
.Where(p => p.Key != null)
.ToDictionary(p => p.Key, p => p.Value);