List inside list does not print elements, instead shows System.Collections.Generic.List`1[System.Object]

前端 未结 3 1882
醉酒成梦
醉酒成梦 2020-12-11 10:00

I have a list which contains three items. First element is integer, second one is also an integer and third one is another list. By using for each loop I\'m able to print th

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-11 10:35

    As per MKasprzyk's answer, you can check the type of each object when iterating through the main list to decide how to output it to the console. Otherwise the default ToString() method will be called (see below).

    If you are using C# 7, you can (arguably) increase readability by using switch pattern matching and simply write:

    foreach (var i in mainList)
    {
        switch (i)
        {
            case IEnumerable li:
                Console.WriteLine($"List: {string.Join(", ", li)}");
                break;
            default:
                Console.WriteLine(i);
                break;
        }
    }
    
    

    This way, non-enumerable objects are output as at present, whereas objects that implement the IEnumerable interface, such as a List are output on a single line, comma separated, with each list value output using the object's ToString() method, e.g.:

    23

    45

    List: 12, 54, 69, ...

    Why are List values appearing like this?

    System.Collections.Generic.List`1[System.Object]
    

    Looking at the documentation for the List class, the ToString() method is derived directly from the base Object class, where it simply outputs the Type name. There is no specific override for this class to make it do something special.

    You could define your own generic class derived from List that overrides the ToString() operator to show items in a particular way if you desired, rather than having special cases in your console output code:

    public class ConsoleFriendlyList : List
    {
        public override string ToString()
        {
            return $"List: {string.Join(", ", this)}";
        }
    }
    

    Now if you modified your code to define avlDataList as follows, it would output the same as above:

    var avlDataList = new ConsoleFriendlyList();
    
        

    提交回复
    热议问题