In C#, what does a call to Sort with two parameters in brackets mean?
You have this line of code:
nodes.Sort((x, y) => distances[x] - distances[y]);
You are not passing two parameters to the sort method but you are passing one parameter which is a delegate that takes 2 parameters. You are essentially doing the following but using a lambda notation:
var nodes = new List<int>();
nodes.Sort(SortIt);
And here is the SortIt
method:
private int SortIt(int x, int y)
{
return distances[x] - distances[y];
}
Keep in mind if you did it using the above approach, distances
will have to be a class level field so the SortIt
method can access it. With lambda expressions, this is what you have, it will just capture the distances
variable and this is called a closure. Read this article if you want to know what closures are.
2
solved In C#, what does a call to Sort with two parameters in brackets mean?