I have an ArrayList with instances of a class (in this case 'loan'). This loan class conta开发者_JAVA百科ins a variable 'date'. I want to sort my ArrayList by these date variables in the most optimum way.
The way I have done date sorting before, is to use a List<DateTime>
. but in this case I want to sort a list/arraylist, keeping the rest of the information, so all the information can be used elsewhere
You can use the System.Linq.Enumerable
extension methods Cast<T>
and OrderBy
for this:
ArrayList list;
List<Loan> loanes = (
from loan in list.Cast<Loan>()
orderby loan.Date
select loan).ToList();
You need to make an IComparer<Loan>
that returns x.Date.CompareTo(y.Date)
.
What Slaks said basically to sort in place in the ArrayList you need a custom IComparer implementation, I put a sample below:
public class Loan
{
public DateTime date { get; set; }
}
public class LoanComparer : IComparer
{
public int Compare(object x, object y)
{
Loan loanX = x as Loan;
Loan loanY = y as Loan;
return loanX.date.CompareTo(loanY.date);
}
}
static void Main(string[] args)
{
Loan l1 = new Loan() {date = DateTime.Now};
Loan l2 = new Loan() { date = DateTime.Now.AddDays(-5) };
ArrayList loans = new ArrayList();
loans.Add(l1);
loans.Add(l2);
loans.Sort(new LoanComparer());
}
精彩评论