mercoledì 25 settembre 2013

How To: Sum of nullable int

Ma come si comporta linq quando somma un campo che può contenere null ?

Già mi sono posto questa domanda perchè non mi è mai capitato di beccare un errore simile, posto che il compilatore blocchi int i = null mi rimane solo qualche piccola pillola per ovviare a eventuali problemi provenienti da codice scritto male.

Ma linq mi ha data prova di essere abbastanza solido... quanto meno in questo semplice esempio.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TestSumLinq
{
    class Program
    {
        public class entity
        {
            public int fstValue { get; set; }
            public int? sndValue { get; set; } 
        }

        static void Main(string[] args)
        {
            List<entity> l = new List<entity>();

            l.Add(new entity() { fstValue = 0, sndValue= null});
            l.Add(new entity() { fstValue = 1, sndValue = 2 });
            l.Add(new entity() { fstValue = 2, sndValue = 3 });
            l.Add(new entity() { fstValue = 3, sndValue = 4 });

            // facendo le somme ottengo ?? 

            var r1 = l.Sum(s => s.fstValue);

            var r2 = l.Sum(s => s.sndValue);

            Console.WriteLine("somma campo int : " + r1.ToString());

            Console.WriteLine("somma campo int?: " + r2.ToString());

            Console.ReadKey();
        }
    }
} 


E in bona sostanza rimango piacevolmente colpito .. perchè funziona senza rompersi.

Nessun commento: