Friday, October 19, 2012

Sorting a Generic List of Object in C#


[Student.cs]

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

namespace KeithRull.LetsSortThat
{
   class Student
   {
      private string _name;
      private double _grade;


      public string Name
      {
         get { return _name; }
         set { _name = value; }
      }

      public double Grade
      {
         get { return _grade; }
         set { _grade = value; }
      }


      public Student(string name, double grade)
      {
         this.Name = name;
         this.Grade = grade;
      }
   }
}
[StudentGradeAndNameComparer]
using System;
using System.Collections.Generic;
using System.Text;

namespace KeithRull.LetsSortThat
{
   class StudentGradeAndNameComparer : IComparer<Student>
   {
      #region IComparer<Student> Members

      public int Compare(Student student1, Student student2)
      {
         int returnValue = 1;
         if (student1 != null && student2 == null)
         {
            returnValue = 0;
         }
         else if (student1 == null && student2 != null)
         {
            returnValue = 0;
         }
         else if (student1 != null && student2 != null)
         {
            if (student1.Grade.Equals(student2.Grade))
            {
               returnValue = student1.Name.CompareTo(student2.Name);
            }
            else
            {
               returnValue = student2.Grade.CompareTo(student1.Grade);
            }
         }
         return returnValue;
      }
 
      #endregion
   }
}
[Modified Program.cs v2]
using System;
using System.Collections.Generic;
using System.Text;

namespace KeithRull.LetsSortThat
{
   class Program
   {
      static void Main(string[] args)
      {
         Students students = new Students();

         //add the student to the list
         students.Add(new Student("Tom", 83));
         students.Add(new Student("Joe", 86.4));
         students.Add(new Student("Rudy", 85));
         students.Add(new Student("Chris", 87.2));
         students.Add(new Student("Keith", 85.5));
         students.Add(new Student("Pepe", 75.1));
         students.Add(new Student("Juan", 88.8));
         students.Add(new Student("Pedro", 75.1));
         students.Add(new Student("Pablo", 75.1));
         students.Add(new Student("Jose", 79.3));
         students.Add(new Student("Tommy", 88.9));

         //implement our custom comparer for grades and names
         students.Sort(new StudentGradeAndNameComparer());
         students.Print();
         Console.ReadLine();
      }
   }
}

No comments:

Post a Comment