Get a specific value in an array

1

I'm trying to get only the name of an element from an array . I want to get the name of the first element of the array and also the name of the last element. I put my method in class Carreira

public override string ToString()
    {


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

    }

In the click event 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 in the first and last element of the array . I just want a value.

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

    
asked by anonymous 06.03.2017 / 16:33

2 answers

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;
}
    
06.03.2017 / 16:52
4

The problem is you're not getting the name. The LINQ method that returns the first and last returns the whole object, the only thing you need to do is grab the specific property you want, in this case the name. So:

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

See working on .NET Fiddle . And No Coding Ground . Also placed in my GitHub repository for future reference .

I consider this an abuse of ToString() . It was not meant to be for formatting information, it's exists for debug effect and at most doing some simple conversion, which can already be considered abuse, but everyone does.

    
06.03.2017 / 16:52