-3

I want to update this code to use OrderBy instead of Sort.

 protected void Sort()
        {
            m_Items.Sort(new Comparison<PayArrayItem>(
                delegate (PayArrayItem x, PayArrayItem y)
                {
                    return x.TransactionDate.CompareTo(y.TransactionDate);
                }
                ));
        }
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
Paul White
  • 97
  • 2
  • 10
  • What is the type of `m_Items`? – Chetan Jan 22 '20 at 06:51
  • `m_Items.OrderBy(m => m.TransactionDate)` – Chetan Jan 22 '20 at 06:52
  • 2
    `Sort` will be sorting the list *in situ*, which means it will actually change the list itself, whereas `OrderBy` will return a new (sorted) List (to be precise: an IEnumerable). This fits into the general theme of LINQ and functional programming, I guess it would help you to find a tutorial about LINQ in general to understand the differences completely. – Dennis Jan 22 '20 at 06:54
  • 2
    Since question already have solid copy-paste ready answer I voted to close it as duplicate of more general comparison of Sort vs. OrderBy which shows all kinds of syntax along with explaining differences for each approach. – Alexei Levenkov Jan 22 '20 at 07:03

1 Answers1

2

Well, Sort does in place sorting, i.e. it sorts existing m_Items collection:

protected void Sort() {
  m_Items.Sort((left, right) => left.TransactionDate.CompareTo(right.TransactionDate));
}

On the contrary, Linq OrderBy creates a new IEnumerable<T> which you have to materialize and assign back to the collection:

using System.Linq;

...

protected void Sort() {
  m_Items = m_Items
    .OrderBy(item => item.TransactionDate)
    .ToList(); // Assuming m_Items is List<T>
}

Please, note, that since in case of OrderBy we create an additional List<T> instance, that's why Sort is better choice in your case.

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215