Reputation: 1063
I created 2 dimensional list in C#, when I want to print the items, it didn't show anything, but the list is not empty.
public static List<List<string>> GetSymetricOrder(List<List<string>> main_list){
List<List<string>> new_main_list = new List<List<string>>();
List<string> list = new List<string>();
for(int i=0;i<main_list.Count;i++){
for(int j=0;j<main_list[i].Count;j+=2){
list.Add(main_list[i][j]);
}
if(main_list[i].Count % 2 == 0){
for(int k = main_list[i].Count-1;k>=0;k-=2){
list.Add(main_list[i][k]);
}
}else{
for(int l = main_list[i].Count-2;l>=0;l-=2){
list.Add(main_list[i][l]);
}
}
new_main_list.Add(list);
list.Clear();
}
return new_main_list;
}
public static void Display(List<List<string>> new_main_list){
int i = 1;
foreach(var list in new_main_list){
Console.WriteLine("SET"+i);
foreach(var s in list){
Console.WriteLine(s);
}
i++;
}
}
public static void Main(string[] args)
{
int num;
List<List<string>> main_list = new List<List<string>>();
List<string> list = new List<string>();
while((num = int.Parse(Console.ReadLine()))!=0){
for(int i=0;i<num;i++){
string input = Console.ReadLine();
list.Add(input);
}
main_list.Add(list);
list.Clear();
}
List<List<string>> SymetricOrder = GetSymetricOrder(main_list);
if(SymetricOrder != null){
Display(SymetricOrder);
}
The code above receive input string in list list
in main method and add the list to main_list
. This will be processed in GetSymetricOrder
and displayed using Display
method. The list is not actually empty because the line:
if(SymetricOrder != null){
Display(SymetricOrder);
}
actually print Console.WriteLine("SET"+i);
inside Display
method, but without list item. Here's the example input:
4
AAA
AA
AAA
AA
3
BBB
BB
BBB
2
RERE
RE
0
and here is the printed result:
SET1
SET2
SET3
No list items were printed, don't know why. Is there anything I missed?, thank you.
Upvotes: 1
Views: 54
Reputation: 3127
The problem is that the "list" variable. You add that to the "main_list" and then clear it => the list inside the "main_list" is cleared as well.
Basically you cannot reuse the "list" variable, since then the "main_list" only contains one instance several times. An easy way to fix it is to just assign a new list to the "list" variable instead of clearing it.
Upvotes: 2