【问题标题】:how to write certain variables in a list to the console C# [closed]如何将列表中的某些变量写入控制台 C# [关闭]
【发布时间】:2018-04-23 00:50:09
【问题描述】:
Stylist stylist1 = new Stylist(); // creates new stylist
stylist1.FirstName = "john";
stylist1.LastName = "smith";
stylist1.Phone = "123456789";
stylist1.Email = "js@123.456";
stylist1.Rate = "123";

Stylist stylist2 = new Stylist(); // creates new stylist
stylist2.FirstName = "jane";
stylist2.LastName = "doe";
stylist2.Phone = "987654321";
stylist2.Email = "jd@987.654";
stylist2.Rate = "456";

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

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

我想将列表的内容显示到控制台,但我只想显示FirstNameLastName,我该怎么做呢?我还制作了一个名为 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; }
}

编辑

如果我从列表中单独写出每一个,我就能写出我需要的东西

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

我尝试过使用foreach

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

但这只会打印“ACW_Programming2.Stylist”

ACW_Programming2 是项目名称

【问题讨论】:

  • 您对此进行过任何研究吗?试过什么?
  • 发布你到目前为止所尝试的内容。

标签: c# list console.writeline


【解决方案1】:
 foreach (var i in stylists)
{
    Console.WriteLine(i.FirstName + " " + i.LastName);
}

【讨论】:

    【解决方案2】:

    作为 Giorgi 回答的替代方案,您可以覆盖 Stylist 的 ToString 方法

    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; }
    
        public override string ToString()
        {
            return FirstName + " " + LastName;
        }
    }
    

    然后做你做的事

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

    【讨论】:

      猜你喜欢
      • 2016-12-01
      • 2015-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-29
      • 2010-09-08
      相关资源
      最近更新 更多