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
166 views
in Technique[技术] by (71.8m points)

I got a problem with a simple List in C#(not displaying the actually list)

List<int> MyList = new List<int>();
MyList.Add(1);
MyList.Add(2);
MyList.Add(3);
MyList.Add(4);
foreach(int item in MyList){
    System.Console.WriteLine(MyList);
}

This is what my code shows :

System.Collections.Generic.List`1[System.Int32]
System.Collections.Generic.List`1[System.Int32]
System.Collections.Generic.List`1[System.Int32]
System.Collections.Generic.List`1[System.Int32]
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

When you ToString an object (which is what Console.WriteLine does), and it hasn't overridden ToString() it writes the name of the class. However, you can just use item which looks like a simple mistake

var myList = new List<int> { 1, 2, 3, 4 };

foreach (var item in myList)
   System.Console.WriteLine(item);

// or, you can get fancy with string.Join

Console.WriteLine(string.Join(", ", myList));

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

1.4m articles

1.4m replys

5 comments

57.0k users

...