Can you tell me why am I getting the following result from this code
public static void CountSort(List<List<string>> arr)
{
for (int i = 0; i < arr.Count / 2; i )
arr[i][1] = "-";
List<List<string>> result = Enumerable.Repeat(new List<string>(), arr.Count).ToList();
for (int i = 0; i < arr.Count; i )
{
string tempValue = arr[i][1];
int index = int.Parse(arr[i][0]);
result[index].Add(tempValue);
}
}
The result is multi dimension List of strings. Whenever the loop goes through, it adds that temp value to all of the sub arrays rather than adding it to the one I want to add it based on index.
I am breaking my head now trying to figure out why is that.
Output looks something like this:
List<List<string>("1"), List<string>("1"),List<string>("1")>
Output I am expecting is :
List<List<string>(), List<string>("1"), List<string>()>
CodePudding user response:
Look at this line:
result = Enumerable.Repeat(new List<string>(), arr.Count).ToList();
This creates one List<string>
instance and repeats this instance in the resulting enumerable/list. Again, only one List<string>
instance is being created here. Regardless which index you are using on result to get a sub list, it's always the same List<string> instance.
Thus, your code adds the temp values to all sub lists, because all the sub lists are in reality just the same single List<string> instance.
Solution: Instead of using Enumerable.Repeat
(which just repeats the given List<string> instance instead of creating new List<string> instances) just do it the old-fashioned way and create all the required List<string> instances yourself:
List<List<string>> result = new();
for (int i = 0; i < arr.Count; i)
result.Add(new List<string>());