Let's say I have a list of objects, and I want to sort it by the items DateModified property. Why can't I use a delegate like this? How should I sort these by DateModified if not as shown below:
public string SortByDateModified(List<CartItem> items) { items.Sort(new Func<CartItem, CartItem, bool>((itemA, itemB) => { return itemA.DateModified < itemB.DateModified; })); }
Why not use a lambda expression?
public string SortByDateModified(List<CartItem> items) { items.Sort((a, b) => a.DateModified.CompareTo(b.DateModified)); }
If you don't want to use lambdas or greater than .NET 2.0, use this:
public string SortByDateModified(List<CartItem> items) { items.Sort(delegate(CartItem itemA, CartItem itemB) { return itemA.DateModified.CompareTo(itemB.DateModified); }); }
In my experience, in environments such as Unity, lambdas and even delegates can cause crashes or problems, especially on platforms like iOS. In that case you would want to make your sorter a separate function like so:
int SortCartItemFunction(CartItem itemA, CartItem itemB) { return itemA.DateModified.CompareTo(itemB.DateModified); }
Then you could pass it to your sort call like this:
items.Sort(SortCartItemFunction);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With