简体   繁体   中英

Show a list in ToString override method

I was wondering if it's possible to show a List inside the public override string ToString() method, so when I list all the properties I also can see each element of a List<> there.

This is my ToString() method:

public override string ToString()
{
    return this.Employees; //Here would be the list
}

And this would be the constructor for Employees with the properties that I wish to list. For example: Employee: John Doe, Employee: Brian Johnson, Employee: Eric Dunn.

public Employee(string fullname)
{
   this.FullName = fullname;
}
public override string ToString()
{
   StringBuilder t = new StringBuilder();
   foreach(Employee e in this.Employees)
   t.AppendLine (string.Format ("Employee: {0}",e.Fullname));
   return t.ToString ();
}

Or

public override string ToString ()
{
  return String.Join ("Employee: ", this.Employees.Select (e => e.Fullname).ToArray<string>());
}

You could try to override ToString as below:

public override string ToString()
{
    return string.Join(",", this.Employees
                                .Select(employee => $"Employee: {employee.FullName}"));
}

If I understand your requirement correctly, the following classes with override .ToString() will solve your issue. Here I'm using two classes one with Employee details and another with List of first classes

public class Employee
{
    public int EmpCode { get; set; }
    public string FullName { get; set; }

    public override string ToString()
    {
        return String.Format("Employee Code : {0} \n Employee Full Name : {1}", this.EmpCode, this.FullName);
    }
}

public class EmployList
{
    public List<Employee> EmployeeList = new List<Employee>();
    public override string ToString()
    {
        StringBuilder strBuilder = new StringBuilder();
        foreach (var item in EmployeeList)
        {
            strBuilder.AppendLine(item.ToString());
        }

        return strBuilder.ToString();
    }
}

How to use the Above classes

EmployList listObject = new EmployList();
listObject.EmployeeList.Add(new Employee(){EmpCode=1,FullName="suji"});
listObject.EmployeeList.Add(new Employee(){EmpCode=11,FullName="jon"});
listObject.EmployeeList.Add(new Employee(){EmpCode=12,FullName="anu"});
listObject.EmployeeList.Add(new Employee(){EmpCode=13,FullName="achu"});

Console.WriteLine(listObject.ToString());

Working Example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM