Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将字典转换为另一个具有不同键类型的字典_C#_.net_Linq - Fatal编程技术网

C# 将字典转换为另一个具有不同键类型的字典

C# 将字典转换为另一个具有不同键类型的字典,c#,.net,linq,C#,.net,Linq,鉴于: 是否有一种简洁的LINQ转换方法: IDictionary==>IDictionary 以下要点: 类型KeyType1的2个值映射到相同的KeyType2 编辑查找可能返回空值,即映射可能不完整。在这种情况下,这些条目应该从新词典中删除 为了避免需要两次查找,您可以首先创建一个字典,将旧键映射到新键: class KeyType1{...} class KeyType2{...} class ValueType{...} public KeyType2 Lookup(KeyType

鉴于:

是否有一种简洁的LINQ转换方法:

IDictionary
==>
IDictionary

以下要点:

  • 类型
    KeyType1
    的2个值映射到相同的
    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
?@Jodrell
Lookup
是一种方法,如果不清楚,很抱歉(为了便于阅读,请随意编辑)
 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);