Thursday, June 5, 2014

CSharp C# Simple Example of sorting a list on a custom object class field value

CSharp C# Simple Example of sorting a list on a custom object class field value









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

namespace TestObjectSort
{
    class Program
    {
        static void Main(string[] args)
        {
            List<InfoHolder> ih = new List<InfoHolder>();
            ih.Add(new InfoHolder(17, "seventeen"));
            ih.Add(new InfoHolder(2, "two"));
            ih.Add(new InfoHolder(3, "three"));
            ih.Add(new InfoHolder(-20, "negative 20"));
            ih.Add(new InfoHolder(500, "five hundred"));
            ih.Add(new InfoHolder(50, "fifty"));

            {
                Console.WriteLine();
                Console.WriteLine("Before sort:");
                for (int x = 0; x < ih.Count; x++)
                {
                    InfoHolder hNow = ih[x];
                    Console.WriteLine("FirstVar = {0} and SecondVar = {1}", hNow.FirstVar, hNow.SecondVar);
                }
            }


            ih.Sort(delegate(InfoHolder ihnow1, InfoHolder ihnow2) { return ihnow1.FirstVar.CompareTo(ihnow2.FirstVar); });

//Note:  To sort in descending order, after Sort above,  call Reverse

            {
                Console.WriteLine();
                Console.WriteLine("After sort:");
                for (int x = 0; x < ih.Count; x++)
                {
                    InfoHolder hNow = ih[x];
                    Console.WriteLine("FirstVar = {0} and SecondVar = {1}", hNow.FirstVar, hNow.SecondVar);
                }
            }

            Console.WriteLine("Done - hit enter to complete.");
            Console.ReadLine();
        }
    }

    public class InfoHolder
    {
        public int FirstVar;
        public string SecondVar;
        public InfoHolder(int firstVar, string secondVar)
        {
            FirstVar = firstVar;
            SecondVar = secondVar;
        }
    }
}


No comments:

Post a Comment