generic comparable : IComparable « Class « Visual C++ .NET






generic comparable

 
#include "stdafx.h"

using namespace System;

enum class SortByEnum
{
   SortByDate,
   SortByFrom,
   SortBySubject
};

ref class MyEmail : IComparable<MyEmail^>
{
   public:

   static property SortByEnum SortCriterion;

   property DateTime DateReceived;
   property String^ From;
   property String^ Subject;
   property String^ Body;

   MyEmail(DateTime dt, String^ from, String^ subject, String^ body)
   {
      DateReceived = dt;
      From = from;
      Subject = subject;
      Body = body;
   }

   virtual int CompareTo(MyEmail^ msg)
   {

       switch ( SortCriterion )
       {
           case SortByEnum::SortByDate:
              return this->DateReceived.CompareTo(msg->DateReceived);
           case SortByEnum::SortByFrom:
              return this->From->CompareTo(msg->From);
           case SortByEnum::SortBySubject:
              return this->Subject->CompareTo(msg->Subject);
           default:
              throw gcnew InvalidOperationException();
       }

   }
};

void PrintHeaders(array<MyEmail^>^ messages, SortByEnum sortOrder){
   MyEmail::SortCriterion = sortOrder;
   Array::Sort(messages);

   for (int i = 0; i < messages->Length; i++)
   {
       Console::WriteLine("Received: {0} From: <{1}> Subject: {2}",messages[i]->DateReceived, messages[i]->From,messages[i]->Subject );
   }
}

int main(){
   array<MyEmail^>^ message_array ={
      gcnew MyEmail( DateTime(2006, 1, 12), "N", "D", ""),
      gcnew MyEmail( DateTime(2006, 1, 15), "G", "B", ""),
      gcnew MyEmail( DateTime(2006, 1, 2), "G", "B", ""),
      gcnew MyEmail( DateTime(2005, 12, 31), "J","W", "")
   };

   PrintHeaders(message_array, SortByEnum::SortByDate);
   PrintHeaders(message_array, SortByEnum::SortByFrom);
   PrintHeaders(message_array, SortByEnum::SortBySubject);

}

   
  








Related examples in the same category