gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 23:15:39 25 4
gpt4 key购买 nike

给定:

class KeyType1{...}
class KeyType2{...}
class ValueType{...}

public KeyType2 Lookup(KeyType1 value)
{
// Returns a unique value of KeyType2 or otherwise, null
}

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

IDictionary<KeyType1,ValueType> ==> IDictionary<KeyType2,ValueType>

以下要点:

  • 没有 2 个类型为 KeyType1 的值映射到相同的 KeyType2
  • 编辑 有可能Lookup可能返回 null,即映射可能不完整。在这种情况下,新词典中应删除这些条目

最佳答案

好的,假设 Lookup 是一个返回可以为 null 的引用类型的函数。

b = a
.Select(p => new { Key = Lookup(p.Key), p.Value }))
.Where(p => p.Key != null)
.ToDictionary(p => p.Key, p => p.Value);

关于c# - 将一个字典转换为另一个具有不同键类型的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37326103/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com