public class Student
{ private int id; public int Id
{
get { return id; }
set { id = value; }
}
private string name; public string Name
{
get { return name; }
set { name = value; }
} private DateTime admissionDate; public DateTime AdmissionDate
{
get { return admissionDate; }
set { admissionDate = value; }
} }
//ready list and call List<Student> stdList = new List<Student> {
new Student{Id=1,Name="A", AdmissionDate = DateTime.Now.AddDays(-100)},
new Student{Id=2,Name="B", AdmissionDate = DateTime.Now.AddDays(-10)},
new Student{Id=3,Name="C", AdmissionDate = DateTime.Now.AddDays(-101)},
new Student{Id=4,Name="D", AdmissionDate = DateTime.Now.AddDays(-102)},
new Student{Id=5,Name="E", AdmissionDate = DateTime.Now.AddDays(-107)},
new Student{Id=6,Name="F", AdmissionDate = DateTime.Now.AddDays(-106)},
new Student{Id=7,Name="G", AdmissionDate = DateTime.Now.AddDays(-11)},
new Student{Id=8,Name="H", AdmissionDate = DateTime.Now.AddDays(-150)},
new Student{Id=9,Name="I", AdmissionDate = DateTime.Now.AddDays(-150)},
new Student{Id=10,Name="J", AdmissionDate = DateTime.Now.AddDays(-170)},
new Student{Id=11,Name="K", AdmissionDate = DateTime.Now.AddDays(-160)},
new Student{Id=12,Name="L", AdmissionDate = DateTime.Now.AddDays(-170)},
new Student{Id=13,Name="M", AdmissionDate = DateTime.Now.AddDays(-130)},
new Student{Id=14,Name="N", AdmissionDate = DateTime.Now.AddDays(-120)},
new Student{Id=15,Name="O", AdmissionDate = DateTime.Now.AddDays(-30)},
new Student{Id=16,Name="P", AdmissionDate = DateTime.Now.AddDays(-120)},
new Student{Id=17,Name="Q", AdmissionDate = DateTime.Now.AddDays(-80)},
new Student{Id=18,Name="R", AdmissionDate = DateTime.Now.AddDays(-104)},
};
DateTime minDate;
DateTime maxDate;
ExtensionCLS.GetMinMaxDate(stdList, "AdmissionDate",out minDate, out maxDate);
string outPutString = "The Mindate Is:" + minDate + " The max date Is:" + maxDate;
Console.WriteLine(outPutString);
Console.ReadLine();
}
public static void GetMinMaxDate<T>(this List<T> source, string valueField, out DateTime minDate, out DateTime maxDate)
{ List<T> obsColl = new List<T>(); DateTime _maxDate = DateTime.Now; DateTime _minDate = DateTime.Now; if (source.Count > 0)
{ foreach (T element in source)
{ if (element.GetType().GetProperty(valueField).GetValue(element, null) != null)
{ obsColl.Add(element); } } _minDate = (DateTime)(dynamic)(from obj in obsColl select obj.GetType().GetProperty(valueField).GetValue(obj, null)).Min(); _maxDate = (DateTime)(dynamic)(from obj in obsColl select obj.GetType().GetProperty(valueField).GetValue(obj, null)).Max(); } minDate = _minDate; maxDate = _maxDate; }
Output: The Mindate Is:11/29/2012 2:16:11 AM The max date Is:5/8/2013 2:16:11 AM