简体   繁体   中英

C# Dynamic list of objects

i have a small entity "Category"

Id
Name 
Parent_id

I want to override the ToString() with a string of all parents of the item and i dont know how many parents the item have.

Example: (pseudo code)
Item1 =>  Id = 1, Name = Computers, Parent_id = null 
Item2 =>  Id = 2, Name = Laptops  , Parent_id = 1
Item3 =>  Id = 3, Name = Acer     , Parent_id = 2

On the output from Item3.ToString() i want the result to be "Computers > Laptops > Acer" . And i need it to be dynamic so i dont know how many steps it should take... Any fresh idéas?

You need to do this recursively:

public overrides string ToString()
{
    string build = parent.ToString();
    if (!String.IsNullOrEmpty(build)) build += " > ";
    build += Name;
    return build
}

Something along the lines of the above should do it - each Entity will call ToString on its parent so you get the list of all entities in the hierarchy. This will work however deep the hierarchy gets (within reason).

Note: you'll need a reference to the parent to do this, either you can use a property, or you can look the entity up using the parentid property you've already got.

First, you need to add the parent item itself (not just the ID) to every item, then it should be easy enough with simple loop:

public override string ToString()
{
    List<string> names = new List<string>();
    names.Add(this.Name);
    Category parent = this.Parent;
    while (parent != null)
    {
        names.Add(parent.Name);
        parent = parent.Parent;
    }
    names.Reverse();
    return string.Join(" > ", names);
}
public class Category
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Category Parent { get; set; }

    public override string ToString()
    {
        return Parent == null 
            ? Name
            : string.Format("{0} > {1}", Parent, Name);
    }
}

Usage:

item1 = new Category{Id = 1, Name = "Computers"};
item2 = new Category{Id = 2, Name = "Laptops", Parent = item1};
item3 = new Category{Id = 3, Name = "Acer", Parent = item2};

Debug.Print(item3.ToString());
Debug.Print(item2.ToString());
Debug.Print(item1.ToString());

Result:

Computers > Laptops > Acer
Computers > Laptops
Computers

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