简体   繁体   English

在 C# 中,使用括号中的两个参数调用 Sort 是什么意思?

[英]In C#, what does a call to Sort with two parameters in brackets mean?

I recently came across an implementation of Djikstra's Shortest Path algorithm online and found the following call.我最近在网上遇到了 Djikstra 的最短路径算法的实现,并发现了以下调用。 given a List of nodes of type int and a Dictionary of distances, of type , what does the following call mean给定一个类型为 int 的节点列表和一个类型为距离的字典,下面的调用是什么意思

nodes.Sort((x, y) => distances[x] - distances[y]);

The full code is as follows:完整代码如下:

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;
}

I searched for the answer a lot but there doesn't seem to be any clear explanation of what it means.我搜索了很多答案,但似乎没有明确解释它的含义。 I do know that in general in LINQ, a call to Array.Select((x,i)=>...) means that x is the actual element in the array and i is the index of element x in the array, but this doesn't seem to be the case above.我知道一般在 LINQ 中,对 Array.Select((x,i)=>...) 的调用意味着 x 是数组中的实际元素,而 i 是数组中元素 x 的索引,但是上面的情况似乎并非如此。

Would appreciate any explanation thanks.将不胜感激任何解释谢谢。

Sorting is implemented by comparing two items at a time.排序是通过一次比较两个项目来实现的。

The two parameters in parentheses are the two items the callback function should compare.括号中的两个参数是回调函数应该比较的两项。

List.Sort Method takes an optional comparison delegate as a comparer. List.Sort 方法采用可选的比较委托作为比较器。

https://msdn.microsoft.com/en-us/library/w56d4y5z(v=vs.110).aspx https://msdn.microsoft.com/en-us/library/w56d4y5z(v=vs.110).aspx

in your example:在你的例子中:

(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;

This method will sort the elements in the entire List using the specified System.Comparison.此方法将使用指定的 System.Comparison 对整个 List 中的元素进行排序。 Where System.Comparison is a delegate System.Comparison 是代表的地方

public delegate int Comparison<in T>(
    T x,
    T y
)

Think of it like this, you are passing the sort method a way to decide which element in the array is a precedent to the other.可以这样想,您正在通过 sort 方法确定数组中的哪个元素是另一个元素的先例。 The sort function will use the compare function you specified to determine the precedence of each element in the returned sorted list. sort 函数将使用您指定的比较函数来确定返回的排序列表中每个元素的优先级。 Therefore this function will get two elements and it will return a value indicating the result of the precendence.因此,此函数将获得两个元素,并将返回一个指示优先结果的值。

let x be the first argument and y the second argument.设 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

In conclusion, this function you pass to the Sort method will help the Sort function to sort the array as you wish it should sort it.总之,您传递给 Sort 方法的这个函数将帮助 Sort 函数按照您希望的方式对数组进行排序。

In C#, what does a call to Sort with two parameters in brackets mean?在 C# 中,使用括号中的两个参数调用 Sort 是什么意思?

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.您没有将两个参数传递给 sort 方法,而是传递了一个参数,该参数是一个带有 2 个参数的委托。 You are essentially doing the following but using a lambda notation:您实际上是在执行以下操作,但使用的是lambda符号:

var nodes = new List<int>();
nodes.Sort(SortIt);

And here is the SortIt method:这是SortIt方法:

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.请记住,如果您使用上述方法进行操作,则distances必须是类级别字段,以便SortIt方法可以访问它。 With lambda expressions, this is what you have, it will just capture the distances variable and this is called a closure .使用lambda表达式,这就是你所拥有的,它只会捕获distances变量,这称为闭包 Read this article if you want to know what closures are.如果你想知道闭包是什么,请阅读这篇文章。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM