在列表中查找项目的位置 - 第一个,最后一个

时间:2012-12-11 16:12:43

标签: c#

我目前正在处理程序开头加载的项目列表。我想确定每个项目的位置。所以我有按钮First显示第一个项目(当前),Next显示第一个(Current.Next)之后的以下项目,Last应该显示最后一个项目但是它没有显示什么都没有。按钮单击名为labelSpecificTree的标签后显示结果。我尝试在Last按钮点击行Current = Trees.Last;内设置中断以查看结果,但没有给我任何具体细节。如何通过标签显示列表中的最后一项?

代码

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }


        ListOfTrees Trees = new ListOfTrees();
        FruitTrees Tree;
        FruitTrees Current;

        double Total;



        public class ListOfTrees
        {
            private int size;

            public ListOfTrees()
            {
                size = 0;
            }

            public int Count
            {
                get { return size; }
            }

            public FruitTrees First;
            public FruitTrees Last;

             public int Add_Initialize(FruitTrees NewItem)
             {
                 NewItem.Next = First;
                 First = NewItem;
                 Last = First.Next;

                 if (Last == null)
                 {
                     Last = First;
                 }

                 return size++;
             }

            public int Add(FruitTrees newItem)
            {
                if (First == null)
                    return Add_Initialize(newItem);

                FruitTrees item = First;
                while (item.Next != null)
                {
                    item = item.Next;
                }

                item.Next = newItem;
                return size++;
            }



        }




        public void Clear()
        {
            textBoxType.Clear();
            textBoxHeight.Clear();
            textBoxPrice.Clear();
            textBoxStock.Clear();
        }


        public void Current_Tree()
        {
            Current = Trees.First;
            labelSpecificTree.Text = Current.Type.ToString();
        }


        private void Form1_Load_1(object sender, EventArgs e)
        {

            Tree = new FruitTrees();
            Tree.Stock = 15;
            Tree.Type = "Pear";
            Tree.Price = 49.99;
            Tree.Height = 20;
            Total += Tree.Price * Tree.Stock;
            Trees.Add(Tree);

            ShowTrees();
            Current_Tree();
        }


        private void buttonLast_Click(object sender, EventArgs e)
        {
            Current = Trees.Last;
            labelSpecificTree.Text = Current.Type.ToString();
        }
    }
}

2 个答案:

答案 0 :(得分:2)

在您的代码中,当您使用“添加”添加新项目时,不会移动“上一步”。试试这个:

public int Add(FruitTrees newItem)
{
    if (First == null)
    return Add_Initialize(newItem);

    FruitTrees item = First;
    while (item.Next != null)
    {
        item = item.Next;
    }

    item.Next = newItem;
    Last = newItem;
    return size++;
}

答案 1 :(得分:1)

您没有在ListOfTrees.Add()方法中设置Last。

尝试在return size++;声明之前添加此权利:

Last = newItem;