Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
471 views
in Technique[技术] by (71.8m points)

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

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 these items.

List<object> mainList= new List<object>();

mainList.Add(binRead.ReadInt32()); // Reads first integer ant adds to mainList
mainList.Add(binRead.ReadInt32()); // Reads second integer ant adds to mainList

List<object> avlDataList = new List<object>();

for(int i=0; i<n; i++)
{
  // Reads some data and adds it to avlDataList
}

mainList.Add(avlDataList); // Adds that list to mainList

foreach(var i in mainList)
{
   Console.WriteLine(i); // Prints items      
}

I get this output:

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

How can I modify my code to see what's inside of that list instead of getting this message? That avlDataList list has 10 elements. So i would like to see 12 elements in total.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try use code below:

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        List<object> mainList = new List<object>();

        mainList.Add(1); 
        mainList.Add(2); 

        List<object> avlDataList = new List<object>();

        for (int i = 0; i < 10; i++)           
            avlDataList.Add(100 + i);  

        mainList.Add(avlDataList); 

        foreach (var i in mainList)
        {
            if (i.GetType() != avlDataList.GetType())
                Console.WriteLine(i);  

            if (i.GetType() == avlDataList.GetType())                
                foreach (var ii in avlDataList)
                    Console.WriteLine(ii); 
        }
    }
}

output: 1 2 100 101 102 103 104 105 106 107 108 109


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...