Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ok, this worked. what is it exactly?

I just lifted this snippet from a website and it proved to be exactly the solution I needed for my particular problem.

I have no idea what it is (particularly the delegate and return parts) and the source doesn't explain it.

Hoping SO can enlighten me.

myList.Sort(  delegate(KeyValuePair<String, Int32> x, KeyValuePair<String, Int32> y) 
              { 
                return x.Value.CompareTo(y.Value); 
              }
            );
like image 774
fieldingmellish Avatar asked Nov 20 '09 04:11

fieldingmellish


1 Answers

MyList.Sort has one parameter - the function that is responsible for comparing items, so the list can be sorted accoding to it.

Next: delegate(x,y) defines the function itself which accepts two parameters of type KeyValuePair[String, Int32].

The content in the brackets {...} is the actual comparisson logic:

return x.Value.CompareTo(y.Value);

which compares 2 integer values according to this definition.

Thus your list will be sorted based on the values of those integers in the accending order.


With C# 3.5 I would rewrite it like this:

mylist.Sort((x,y) => x.Value.CompareTo(y.Value));
like image 66
Dmytrii Nagirniak Avatar answered Sep 22 '22 11:09

Dmytrii Nagirniak