简体   繁体   中英

Override ToString() method with List<>

What I have tried so far:

private List<Item> item = new List<Item>();

    public List<Item> Item { get; set; } //Provide Access to List item

    public Inventory() // Default constructor made to initialize default List<> value
    {
        Item = new List<Item>()
        {
            new Item("iPod"),
            new Item("Samsung"),
            new Item("Motorolla"),
            new Item("Nokia")
        };
    }

override String ToString() {
  return ...?
}

How do I implement an override ToString() method in my class that returns the default List<> values to the user

Thanks, appreciate it.

Since you state that you've already overrided the ToString() method for individual list items, you can do something like this:

public override string ToString()
{
   return string.Join(", ", item);
}

So, assuming your Item's ToString() method just returns the string you pass in to create it, you would end up with a string like this: iPod, Samsung, Motorola, Nokia .

If your list is likely to grow to a large amount, and you just want a preview, you could take the first 5 items to build the string from like so:

public override string ToString()
{
   return string.Join(", ", item.Take(5));
}

By the way, I'd recommend calling your Item property Items since it is a collection and not a single item.

Example here .

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