Get a specific value in an array

Asked

Viewed 907 times

1

I’m trying to get just the name of an element of a array. I want to get the name of the first element of array and also the name of the last element. I put my method in the class Carreira

public override string ToString()
    {


        return "Carrer: " + NrCarreira + "\n1st stop: " + VecParagem.First() + "\nlast stop: " + vecParagem.Last();

    }

At the event click I have this:

Paragem[] vec1 = new Paragem[3];

        vec1[0] = new Paragem(1, "Nome1", "Porto");
        vec1[1] = new Paragem(2, "Nome2", "Maia");
        vec1[2] = new Paragem(3, "Nome3", "Matosinhos");

        Carreira c1 = new Carreira(4, true, true, vec1);

        label5.Text = c1.ToString();

But I get the career number that is correct, but also all the information from the first and last element of the array. I just want a value.

What I need to change in my method ToString()?

  • Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site (when you have enough score).

2 answers

4

The problem is you’re not taking the name. The LINQ method that returns the first and the last returns the whole object, the only thing you need to do is take the specific property you want, in this case the name. Thus:

public override string ToString() {
    return "Carrer: " + NrCarreira + "\n1st stop: " + VecParagem.First().Nome + "\nlast stop: " + vecParagem.Last().Nome;
}

using static System.Console;
using System.Linq;

public class C {
    public static void Main() {
        var vec1 = new Paragem[3] {
                new Paragem(1, "Nome1", "Porto"),
                new Paragem(2, "Nome2", "Maia"),
                new Paragem(3, "Nome3", "Matosinhos") };
        WriteLine($"Primeiro {vec1.First().Nome} - Ultimo {vec1.Last().Nome}");
    }
}
public class Paragem {
    public Paragem(int id, string nome, string nome2) {
        Id = id;
        Nome = nome;
        Nome2 = nome2;
    }

    public int Id { get; set; }
    public string Nome { get; set; }
    public string Nome2 { get; set; }
}

Behold working in the ideone. And in the .NET Fiddle. Also put in my Github repository for future reference.

I consider this an abuse of ToString(). It was not made to format information, it exists for the purpose of debug and at most make some simple conversion, which can already be considered abuse, but everyone does.

3


Assuming the property you want to display is Nome:

public override string ToString()
{
    return "Carrer: " + NrCarreira 
        + "\n1st stop: " + VecParagem.First().Nome 
        + "\nlast stop: " + VecParagem.Last().Nome;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.