[英]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.