Saturday, 27 May 2017

LINQ 04 OrderBy

you can use linq to order the elements within your collection.

using System;
using System.Linq;

namespace pc.linq03
{
    class Program
    {
        static void Main(string[] args)
        {
            var nums = Enumerable.Range(0, 10);

            var result1 = nums.OrderByDescending(n => n);
            var result2 = from n in nums
                          orderby n descending
                          select n;

            Array.ForEach(result1.ToArray(), n => Console.Write(n + " "));
            Console.WriteLine();

            Array.ForEach(result2.ToArray(), n => Console.Write(n+ " "));
            Console.WriteLine();
        }
    }
}

Now the above is a simple usage of ordering collection data.

if we are trying to order a collection that contains custom objects, those objects have to implement the IComparable interface.

using System;
using System.Linq;

namespace pc.linq03
{
    class Person : IComparable<Person>
    {
        public string Name { get; set; }
        public int BirthYear { get; set; }
        public Person(string Name, int BirthYear)
        {
            this.Name = Name;
            this.BirthYear = BirthYear;
        }

        public override string ToString() return $"{Name} {BirthYear}"}

        public int CompareTo(Person other)
        {
            if (BirthYear == other.BirthYear)
                return 0;
            else if (BirthYear < other.BirthYear)
                    return 1;
            return -1;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var ppl = new Person[] { new Person("pawel", 1984),
                new Person("Marin", 1983), new Person("Magda", 1984),
                new Person("Tomek",1988), new Person("Ivan", 1987),
                new Person("Trish", 1989), new Person("Jake", 1988)};

            var result1 = ppl.OrderByDescending(p => p);
            var result2 = from p in ppl
                          orderby p descending
                          select p;

            Array.ForEach(result1.ToArray(), n => Console.Write(n + ", "));
            Console.WriteLine();

            Array.ForEach(result2.ToArray(), n => Console.Write(n + ", "));
            Console.WriteLine();
        }
    }
}

If our person class didn't implement the IComparable interface the when trying to order our collection we'd get an exception.