当字典中没有匹配的非空值时,返回null。

问题描述 投票:1回答:4

我有一个类型为整数的字典。当我在我的类中填充了一个类型为 Nullable<int>我想根据给定的产品ID从字典中填入这个属性的值。

当给定的产品id没有对应的值时,我怎样才能得到nullable类型?

public class OrderLine
{
    public int? AvailableQuantity { get; set; }
}

var selectedProductId = Guid.NewGuid();
var products = new Dictionary<Guid, int>
{
    { Guid.NewGuid(), 1 },
    { Guid.NewGuid(), 2 },
    { Guid.NewGuid(), 3 },
};

var result = new OrderLine
{
    Id = Guid.NewGuid(),
    ProductId = selectedProductId,
    AvailableQuantity = products.GetValueOrDefault(selectedProductId, default)
};

上述方法返回 0 而不是 null

而且当我尝试编译时,编译器也无法编译

AvailableQuantity = products.GetValueOrDefault(selectedProductId, default(int?))

TValue System.Collections.Generic.CollectionExtensions.GetValueOrDefault(this IReadOnlyDictionary, TKey, TValue) "方法的类型参数无法从用法中推断出来。请尝试明确指定类型参数。

我无法改变字典的类型。字典是广泛使用的方法的返回类型。这是第一个需要处理产品id不在该字典中的情况。

我想避免用枚举法将字典的类型改为nullable。

c# dictionary collections
4个回答
4
投票

你可以写一个C#扩展,使用 TryGetValue

public static class DictionaryExtensions
{
    public static TValue? GetValueOrNull<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key)
        where TValue : struct
    {
        if (dict.TryGetValue(key, out TValue value))
        {
            return value;
        }

        return null;
    }
}

用途。

products.GetValueOrNull(selectedProductId);

PS:这个扩展也适用于其他类型,除了 int例如 decimal, bool 和其他结构类型


1
投票

如果您只做一次--使用三元运算符。

Quantity = products.TryGetValue(productId, out var qty) ? qty : default(int?)

如果你要在多个地方做,就把上面的代码打包成一个扩展方法


0
投票

你会得到默认值0,因为它是默认值的 int (不可为空)。

要获取 null 将字典中的值的类型更改为 int? (nullable)。

var products = new Dictionary<Guid, int?>
{
    { Guid.NewGuid(), 1 },
    { Guid.NewGuid(), 2 },
    { Guid.NewGuid(), 3 },
};

0
投票

请试一试

var products = new Dictionary<Guid, int?>
{
{ Guid.NewGuid(), 1 },
{ Guid.NewGuid(), 2 },
{ Guid.NewGuid(), 3 },
};
© www.soinside.com 2019 - 2024. All rights reserved.