在C#中排序列表

时间:2014-06-04 10:38:13

标签: c#

我创建了一个列表,其中包含3种不同的值,我希望使用一种值对列表进行排序。我做了这个

      PriorityQueueList.OrderBy(x => x.pQPrioirty).ToList();

但是没有任何问题,只是根据我希望列表中的值显示我的值

     public class Node
    {
         public int name {get; set;}
         public int pQTime { get; set; }
         public int pQPrioirty { get; set; }

        public Node(int _Name, int _PQ, int _PQP)
       {
        this.name = _Name;
        this.pQTime = _PQ;
        this.pQPrioirty = _PQP;
    }
     }


               List<Node> PriorityQueueList = new List<Node>();

               for (int x = 0; x < nodesNumber; x++)
                {
            Label lblName = new Label();
            NumericUpDown numiNumber = new NumericUpDown();

            xCoor = coor.Next(0, 700);
            yCoor = coor.Next(0, 700);

            if (!randomListxCoor.Contains(xCoor))
            {
                randomListxCoor.Add(xCoor);

            }
            if (!randomListyCoor.Contains(xCoor))
            {
                randomListyCoor.Add(yCoor);

            }

            prioritySaver = pQueuNumbers.Next(1, nodesNumber * 3);

            numiNumber.Name = x.ToString();
            numiNumber.Location = new Point(xCoor, yCoor);
            numiNumber.Size = new Size(50, 15);
            numiNumber.Maximum = 100;
            numiNumber.Minimum = 0;


            lblName.Location = new Point(xCoor + 10, yCoor + 15);
            lblName.Text = x.ToString();
            lblName.ForeColor = System.Drawing.Color.Black;
            lblName.AutoSize = true;

            this.pnlNodes.Controls.Add(lblName);
            this.pnlNodes.Controls.Add(numiNumber);

            numberControls.Add(x, 0);
            waytosave.Add(x, 0);
            savePriority.Add(x, prioritySaver);
            Node Node = new Node(x, 0, prioritySaver);
            this.PriorityQueueList.Add(Node);
                }




      private void RunManualPriorityQueue(int nodesNumber)
    {

        PriorityQueueList.OrderBy(x => x.pQPrioirty).ToList();

            } 

我从numricaUpDown获取值我已经检查了值的变化。一切都很好,只是可以使用的排序               PriorityQueueList.OrderBy(x =&gt; x.pQPrioirty)。ToList(); 对列表进行排序,但为什么不按优先级排序。我正在构建优先级队列

2 个答案:

答案 0 :(得分:1)

该方法返回一个有序列表,您不能存储在任何地方。尝试

PriorityQueueList=PriorityQueueList.OrderBy(x => x.pQPrioirty).ToList();

答案 1 :(得分:0)

您没有将已排序的结果分配回列表。试试这个:

private void RunManualPriorityQueue(int nodesNumber)
{
    PriorityQueueList = PriorityQueueList.OrderBy(x => x.pQPrioirty).ToList();

或者您可以使用List<T>.Sort Method (Comparison<T>)进行就地排序,这可能会更有效。