Getting Latest Records
I have list of records in a Xml file,where each record as its date of creation.Can you please suggest me an efficient way in getting the latest two records.
Xml File can be taught of as below:
<Records>
<Record>
<RecordID>1<RecordID&开发者_开发知识库gt;
<CreationDate>Apr 01, 2011 10:15 <CreationDate>
<Record>
<Record>
<RecordID>2<RecordID>
<CreationDate>Jan 12, 2011 10:15<CreationDate>
<Record>
<Record>
<RecordID>3<RecordID>
<CreationDate>Feb 12, 2011 09:00<CreationDate>
<Record>
.
.
.
.
many such records...
<Records>
Will take all this xml into a list,but then can u tell me a efficient way in extracting latest two records out of the list.
Thank you.
You need to store the creation date as a DateTime object and not as a string. Implement a comparison method in your Record class that compares the creation dates. Then if you store your records in a list you should be able to sort it. In the example below the latest records will be at the end, so if you want them just reverse the list.
List<Records> recordList = parseXml(); // populate your list
recordList.Sort(new Comparison<Record>(Record.Comparison)); // sort in creation date ascending order
recordList.Revers(); // reverse the elements in the list
Record[] the2latest = new Record[2]{recordList[0], recordList[1]};
public partial class Record
{
public static int Comparison(Record r1, Record r2)
{
return DateTime.Compare(r1.creationDate, r2.creationDate);
}
}
精彩评论