@arubaito

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

LINQのSumメソッドの戻り値がNull許容型であることに対する疑問

Q&A

解決したいこと

C#でLINQのSumメソッドを使おうとしています。
Sum<TSource>(IEnumerable<TSource>, Func<TSource,Nullable<Int32>>)です)

nullが返らない仕様と実装になっているのに戻り値がint?とNull許容型となっているのはなぜでしょうか?

  • 仕様

Items in source that are null are excluded from the computation of the sum. This method returns zero if source contains no elements or all elements are null.

  • 実装
Sum.cs
public static int? Sum<TSource>(this IEnumerable<TSource> source, Func<TSource, int?> selector)
{
    if (source == null)
    {
        ThrowHelper.ThrowArgumentNullException(ExceptionArgument.source);
    }

    if (selector == null)
    {
        ThrowHelper.ThrowArgumentNullException(ExceptionArgument.selector);
    }

    int sum = 0;
    checked
    {
        foreach (TSource item in source)
        {
            int? v = selector(item);
            if (v != null)
            {
                sum += v.GetValueOrDefault();
            }
        }
    }

    return sum;
}

引数のselectorがNullableだからそれに合わせる、、、みたいな思想があるんですかね?
教えていただけると助かりますm(__)m

0 likes

1Answer

This method returns zero if source contains no elements.. As of why, you should ask MSFTs, for me it's a bug (which due to their backward compatibility policy will never be fixed) because the corresponding IQueryable<T> method works differently when implemented by real (non LINQ to Objects) query provider.

IQueryable<T> の互換都合みたい?

3Like

Comments

  1. @arubaito

    Questioner

    コメントありがとうございます!:bow:

Your answer might help someone💌