2

I have an ArrayList with instances of a class (in this case 'loan'). This loan class contains 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

MichaelMcCabe
  • 523
  • 4
  • 15
  • 33

3 Answers3

3

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();
Steven
  • 166,672
  • 24
  • 332
  • 435
2

You need to make an IComparer<Loan> that returns x.Date.CompareTo(y.Date).

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
1

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());
}
BrokenGlass
  • 158,293
  • 28
  • 286
  • 335