Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: Sorting with anonymous function

Tags:

c#

sorting

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;     })); } 
like image 207
JamesBrownIsDead Avatar asked Jan 23 '10 03:01

JamesBrownIsDead


2 Answers

Why not use a lambda expression?

public string SortByDateModified(List<CartItem> items)  {      items.Sort((a, b) => a.DateModified.CompareTo(b.DateModified));  }  
like image 174
Samuel Neff Avatar answered Sep 28 '22 06:09

Samuel Neff


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); 
like image 31
jjxtra Avatar answered Sep 28 '22 08:09

jjxtra