Pergunta

This is how I get my sum

double? myVar = myList.Sum(x => x.MyItem);

Is-it possible to replace myVar with null if .Sum() return 0 in the same line ?

I don't want to use

if(myVar == 0) myVar = null;

Does LINQ have a post-conditional statement ?

Foi útil?

Solução

It sounds like you want the reverse of the null-coalescing operator, and there's nothing in either LINQ or the C# language to do that for you. You could create your own extension method to do that if you wanted though:

public T? NullIfDefault<T>(this T? value) where T : struct
{
    if (value == null)
    {
        return value;
    }
    return EqualityComparer<T>.Default.Equals(default(T), value.Value)
        ? null : value;
}

Then:

double? myVar = myList.Sum(x => x.MyItem).NullIfDefault();

(There are various other options for how you code NullIfDefault, e.g. using Nullable<T>.GetValueOrDefault() - you might want to play around to find the form you like most.)

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top