显示标签中的所有对象值(WFA)

时间:2015-05-13 15:46:06

标签: c# list object

我想知道如何正确显示标签上列表中的所有对象。

{
class HighScore
{
    public string name;
    public int points;

    public HighScore(string N, int P)
    {
        this.name = N;
        this.points = P;
    }


}

private void Form1_Load(object sender, EventArgs e)
    {
        List<HighScore> score = new List<HighScore>();
        score.Add(new HighScore("Paul", 20));
        score.Add(new HighScore("Robert", 30));
        score.Add(new HighScore("John", 25));
        score.Add(new HighScore("Michael", 300));

        foreach(HighScore per in score)
        {
            label1.Text = per.name + "  " + per.points;
        }
    }
}

我尝试使用foreach循环使标签显示列表中的所有值,但它只显示一个值,而不是所有值。如何在标签上正确显示此列表?

2 个答案:

答案 0 :(得分:0)

首先,您使用=,因此在每次迭代时,您都会替换label1.Text值 作为解决方案,您可以简单地使用+=运算符,因此将附加到label1.Text值。

另一种方式:类中的override ToString方法,例如

public override string ToString(){
    return per.name + "  " + per.points;
}

并使用它label1.Text += per.ToString();
或者string.Join喜欢

private void Form1_Load(object sender, EventArgs e)
{
    List<HighScore> score = new List<HighScore>();
    score.Add(new HighScore("Paul", 20));
    score.Add(new HighScore("Robert", 30));
    score.Add(new HighScore("John", 25));
    score.Add(new HighScore("Michael", 300));

    label1.Text = string.Join(",", score);
}

如果您无法覆盖ToString,则可以使用下一个linq Select

private void Form1_Load(object sender, EventArgs e)
{
    List<HighScore> score = new List<HighScore>();
    score.Add(new HighScore("Paul", 20));
    score.Add(new HighScore("Robert", 30));
    score.Add(new HighScore("John", 25));
    score.Add(new HighScore("Michael", 300));

    label1.Text = string.Join(",", score.Select(per=>per.name + "  " + per.points));
}

答案 1 :(得分:0)

你的解决方案应该像这样“重新制定”:

private void Form1_Load(object sender, EventArgs e)
        {
            List<HighScore> score = new List<HighScore>();
            score.Add(new HighScore("Paul", 20));
            score.Add(new HighScore("Robert", 30));
            score.Add(new HighScore("John", 25));
            score.Add(new HighScore("Michael", 300));
            StringBuilder labelResult = new StringBuilder();
            foreach(HighScore per in score)
            {
                labelResult.Apend(per.name + "  " + per.points+"\n");
            }
            labe1.Text = labelResult.ToString();
        }