Search code examples
c#listconsole.writeline

how to write certain variables in a list to the console C#


Stylist stylist1 = new Stylist(); // creates new stylist
stylist1.FirstName = "john";
stylist1.LastName = "smith";
stylist1.Phone = "123456789";
stylist1.Email = "[email protected]";
stylist1.Rate = "123";

Stylist stylist2 = new Stylist(); // creates new stylist
stylist2.FirstName = "jane";
stylist2.LastName = "doe";
stylist2.Phone = "987654321";
stylist2.Email = "[email protected]";
stylist2.Rate = "456";

List<Stylist> stylists = new List<Stylist>(); // creates stylist 
list

stylists.Add(stylist1);
stylists.Add(stylist2);

i want to display the contents of the list to the console but i only want to display FirstName and LastName, how do i go about doing this? i have also made a custome class called Stylist

public class Stylist
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public string Phone { get; set; }
    public string Rate { get; set; }
}

EDIT

i am able to write what i need if i write each one out separately from the list

Console.WriteLine(stylist1.FirstName + " " + stylist1.LastName);

i have tried using a foreach

foreach (object i in stylists)
{
    Console.WriteLine(i);
}

but this only prints "ACW_Programming2.Stylist

ACW_Programming2 is the project name


Solution

  •  foreach (var i in stylists)
    {
        Console.WriteLine(i.FirstName + " " + i.LastName);
    }