giovedì 21 febbraio 2013

How To: Lambda Distinct.

Ammetto che la soluzione non è assolutamente mia, ma di un nuovo editor che a breve potrà partecipare al Blog.. ben venuto Vittorio.

Il dilemma del giorno è come ottenere l'effetto del distinct SQL tramite lambda...


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

namespace IQuerableDistinct
{
    public class friend
    {
        public string Surname { get; set; }
        public string Name { get; set; }
        public string Nick { get; set; }
        public string Socialpage { get; set; }
    }

    public class friends : List<friend> { };

    class Program
    {
        static void Main(string[] args)
        {

            friend f = new friend() 
                { Surname = "Arosio", 
                  Name = "Fabio", 
                  Nick = "thema!", 
                  Socialpage="" };
            
            friend f1 = new friend() 
                { Surname = "Arosio", 
                  Name = "Fabio", 
                  Nick = "nudrubufu", 
                  Socialpage = "nudrubufu.blogspot.com" };

            friend f2 = new friend() 
                { Surname = "Arosio", 
                  Name = "Fabio", 
                  Nick = "xa", 
                  Socialpage = "deviantArt.com/Thema" };

            friend f3 = new friend() 
                { Surname = "Arosio", 
                  Name = "Fabio", 
                  Nick = "TheMa!", 
                  Socialpage = "flikr.com/213445" };

            friend f4 = new friend() 
                { Surname = "Arosio", 
                  Name = "Fabio", 
                  Nick = "TheMa!", 
                  Socialpage = "500px/FabioArosio" };


            friends fx = new friends();
            fx.Add(f);
            fx.Add(f1);
            fx.Add(f2);
            fx.Add(f3);
            fx.Add(f4);

            foreach (friend x in fx) 
            { 
                Console.WriteLine(x.Surname + 
                        "\t" + x.Name + 
                        "\t" + x.Nick); 
            }

            Console.WriteLine("\r\nDistinct by Surname+Name...");

            var d = fx.GroupBy(c => c.Surname + c.Name).Select(g => g.First());


            foreach (friend x in d)
            {
                Console.WriteLine(x.Surname +
                        "\t" + x.Name );
            }

            Console.ReadLine();
        }
    }
}

Sembra facile ma non è difficile come al solito.

Creaiamo 4 entità che per comodo e per gestire il nostro esempio presentano valori simili... ma differenti per attributi..

La distinct ci permette di comprendere quanti amici abbiamo con lo stesso nome..

Nessun commento: