【发布时间】:2021-04-25 08:16:30
【问题描述】:
我有一个这样的对象:
class Moose
{
public int? DatabaseID; // (null if not stored)
public string Name;
}
List<moose> meese;
我想为那些具有非空 DatabaseID 的 meese 生成一个将 DatabaseID 映射到 Name 的字典。
直达路线不起作用:
Dictionary<int, string> mapIdToName = meese.Where(moose => moose.DatabaseID != null).ToDictionary(moose => moose.DatabaseID, moose => moose.Name);
我明白了
Cannot implicitly convert type 'System.Collections.Generic.Dictionary<int?, string>' to 'System.Collections.Generic.Dictionary<int, string>'
如果我要创建一个列表,我可以这样做:
List<int> databaseIDs = meese.Select(moose => moose.DatabaseID).OfType<int>();
但我找不到与 ToDictionary 类似的内容。
现在我只是手动操作:
Dictionary<int, string> mapIdToName = new Dictionary<int, string>();
foreach (var moose in meese)
{
if (moose.DatabaseID != null)
mapIdToName[moose.DatabaseID] = moose.Name;
}
有没有聪明的 Linq 方法来做到这一点?
编辑
我有
#nullable enable
这样做
Dictionary<int, string> mapIdToName = meese.Where(moose => moose.DatabaseID.HasValue).ToDictionary(moose => moose.DatabaseID.Value, moose => moose.Name);
不会产生错误,但会产生警告“Nullable value type may be null”
【问题讨论】:
标签: c# linq dictionary