如果不是空,则添加到集合

Aab*_*ela 24 c# nullable

我有一个非常大的对象,有许多可空类型的变量.我还有一个字典,我想填写这个对象的非空变量.

代码看起来像这样

if (myObject.whatever != null)
{
myDictionary.Add("...",myObject.whatever);
}
if (myObject.somethingElse != null)
{
myDictionary.Add("...",myObject.somethingElse);

...
Run Code Online (Sandbox Code Playgroud)

编辑(对不起搞砸了代码)

当我们无数次重复这个时,我们会得到一堆很长的代码.有没有更短的方式我可以写这个烂摊子?我知道条件运算符(又名?)但这只是为了分配.是否有类似的东西可以添加到集合中?

Bot*_*000 38

你字典的扩展方法怎么样?

public static void AddIfNotNull<T,U>(this Dictionary<T,U> dic, T key, U value) 
where U : class {
    if (value != null) { dic.Add(key, value); }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以这样做:

myDictionary.AddIfNotNull("...",myObject.whatever);
Run Code Online (Sandbox Code Playgroud)


Tim*_* S. 6

我建议写一个扩展方法:

public static class MyExtensions
{
    public static void AddIfNotNull<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key, TValue value)
    {
        if ((object)value != null)
            dictionary.Add(key, value);
    }
}
Run Code Online (Sandbox Code Playgroud)

使用(object)value != null确保这可以像您期望的那样使用可空类型(例如int?)值类型(例如int)和引用类型(例如SomeClass).如果你将它与之比较default(TValue),那么即使它不是空的int,0也不会添加.如果您包含TValue : class要求,则不能将其Nullable<T>用作类型,这听起来是您最常用的用法.