[英]In C#, what does a call to Sort with two parameters in brackets mean?
我最近在网上遇到了 Djikstra 的最短路径算法的实现,并发现了以下调用。 给定一个类型为 int 的节点列表和一个类型为距离的字典,下面的调用是什么意思
nodes.Sort((x, y) => distances[x] - distances[y]);
完整代码如下:
public List<int> shortest_path(int start, int finish)
{
var previous = new Dictionary<int, int>();
var distances = new Dictionary<int, int>();
var nodes = new List<int>();
List<int> path = null;
foreach (var vertex in vertices)
{
if (vertex.Item1 == start)
{
distances[vertex.Item1] = 0;
}
else
{
distances[vertex.Item1] = int.MaxValue / 2;
}
nodes.Add(vertex.Item1);
}
while (nodes.Count != 0)
{
nodes.Sort((x, y) => distances[x] - distances[y]);
var smallest = nodes[0];
nodes.Remove(smallest);
if (smallest == finish)
{
path = new List<int>();
while (previous.ContainsKey(smallest))
{
path.Add(smallest);
smallest = previous[smallest];
}
break;
}
if (distances[smallest] == int.MaxValue)
{
break;
}
foreach (var neighbor in vertices[smallest].Item2)
{
var alt = distances[smallest] + neighbor.Item2;
if (alt < distances[neighbor.Item1])
{
distances[neighbor.Item1] = alt;
previous[neighbor.Item1] = smallest;
}
}
}
return path;
}
我搜索了很多答案,但似乎没有明确解释它的含义。 我知道一般在 LINQ 中,对 Array.Select((x,i)=>...) 的调用意味着 x 是数组中的实际元素,而 i 是数组中元素 x 的索引,但是上面的情况似乎并非如此。
将不胜感激任何解释谢谢。
排序是通过一次比较两个项目来实现的。
括号中的两个参数是回调函数应该比较的两项。
List.Sort 方法采用可选的比较委托作为比较器。
https://msdn.microsoft.com/en-us/library/w56d4y5z(v=vs.110).aspx
在你的例子中:
(x, y) => distances[x] - distances[y]) is a delegate that Sort uses as a comparer.
if distances[x] - distances[y] < 0; x is bigger;
if distances[x] - distances[y] > 0; y is bigger;
if distances[x] - distances[y] > 0; both are even;
此方法将使用指定的 System.Comparison 对整个 List 中的元素进行排序。 System.Comparison 是代表的地方
public delegate int Comparison<in T>(
T x,
T y
)
可以这样想,您正在通过 sort 方法确定数组中的哪个元素是另一个元素的先例。 sort 函数将使用您指定的比较函数来确定返回的排序列表中每个元素的优先级。 因此,此函数将获得两个元素,并将返回一个指示优先结果的值。
设 x 为第一个参数,y 为第二个参数。
x < y -> the function will return a number less than 0
x = y -> the function will return 0
x > y -> the function will return a number bigger than 0
总之,您传递给 Sort 方法的这个函数将帮助 Sort 函数按照您希望的方式对数组进行排序。
在 C# 中,使用括号中的两个参数调用 Sort 是什么意思?
你有这行代码:
nodes.Sort((x, y) => distances[x] - distances[y]);
您没有将两个参数传递给 sort 方法,而是传递了一个参数,该参数是一个带有 2 个参数的委托。 您实际上是在执行以下操作,但使用的是lambda符号:
var nodes = new List<int>();
nodes.Sort(SortIt);
这是SortIt
方法:
private int SortIt(int x, int y)
{
return distances[x] - distances[y];
}
请记住,如果您使用上述方法进行操作,则distances
必须是类级别字段,以便SortIt
方法可以访问它。 使用lambda表达式,这就是你所拥有的,它只会捕获distances
变量,这称为闭包。 如果你想知道闭包是什么,请阅读这篇文章。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.