I am sorry if this is duplicate. Please point to correct question.
I have a class called MyDate like below
public class MyDate
{
private SqlDateTime m_dateTime;
public MyDate(DateTime dateTime)
{
if (DateTime.Compare(dateTime, (DateTime)SqlDateTime.MinValue) <= 0)
m_dateTime = SqlDateTime.MinValue;
else
m_dateTime = dateTime;
}
public string MMDDYYYYHHMMSS
{
get
{
if(m_dateTime > SqlDateTime.MinValue)
return m_dateTime.Value.ToString("MM/dd/yyyy hh:mm:ss tt");
else
return String.Empty;
}
}
}
I have class called MyEvent like below
public class MyEvent
{
public int EventId{get;set;}
public MyDate StartDate{get;set;}
}
I have collection of MyEvent like
List myEvents.
Now I need to sort myEvents in descending order of StartDate. The problem I have is I cannot add IComparable or change MyDate since it is written by other team and I just refer dll. I donot have control on MyDate code. Can anybody help me how I can do. I created a new comparer class that implements IComparer but unable to understand how to use it and sort myEvents.
**UPDATE 1 **
Thank you very much for Alexei, Ehsan and Dave for helping me out. I tried Dave's answer and it worked. I was trying to do it in more better way so that there is no need to add any new properties. I didnot try Ehsan way of using StringDateComparer but it helped me to understand how I can use Comparer in Order linq statements. At last as pointed by Alexei I did like below
**UPDATE 2 **
Sometimes I am getting empty string for e2.StartDate.MMDDYYYYHHMMSS and/or e2.StartDate.MMDDYYYYHHMMSS so I changed my code like below
myEvents.Sort(
delegate(MyEvent e1, MyEvent e2)
{
DateTime dt1;
DateTime dt2;
DateTime.TryParse(e1.StartDateTime.MMDDYYYYHHMMSS, out dt1);
DateTime.TryParse(e2.StartDateTime.MMDDYYYYHHMMSS, out dt2);
return dt2.CompareTo(dt1); // descending
//return dt1.CompareTo(dt2); // ascending
}
);
No comments:
Post a Comment