I would like to sort List, where last element of the string array is sort key. I need top 5 results.(with lower key)
This works, but I don't want to use LINQ:
...
List<string[]> gameResults = OpenResults(fileLocation);
gameResults.Add(CurrentPlayerResult());
var newOrderedGameResults =
from line in currentGameResults
orderby int.Parse(line.LastOrDefault())
select line;
...
But this don't:
public void SaveResults(string fileLocation = @"..\..\GameResults.txt")
{
// string[] format:
// [0],..,[n-1], [n]
// names, mistakeCount
List<string[]> gameResults = OpenResults(fileLocation);
gameResults.Add(CurrentPlayerResult());
QuickSort(gameResults, 0, gameResults.Count - 1);
try
{
using (StreamWriter resultsFile = new StreamWriter(fileLocation))
{
foreach (var line in gameResults.Take(5))
{
for (int i = 0; i < line.Length - 1; i++)
{
resultsFile.Write("{0} ", line[i]);
}
// dont add " " after last element
resultsFile.WriteLine("{0}", line[line.Length - 1]);
}
}
}
catch (IOException exception)
{
Console.WriteLine("The file could not be write:");
Console.WriteLine(exception.Message);
}
where:
private void QuickSort(List<string[]> listToSort, int left, int right)
{
int pivot = left; //(left + right) / 2;
int leftHold = left;
int rightHold = right;
while (left < right)
{
while (GetScoreFromLine(listToSort[right]) >= pivot && left < right)
{
right--;
}
if (left != right)
{
listToSort[left] = listToSort[right];
left++;
}
while (GetScoreFromLine(listToSort[left]) <= pivot && left < right)
{
left++;
}
if (left != right)
{
listToSort[right] = listToSort[left];
right--;
}
}
listToSort[left] = listToSort[pivot];
pivot = left;
left = leftHold;
right = rightHold;
if (left < pivot)
{
QuickSort(listToSort, left, pivot - 1);
}
if (right > pivot)
{
QuickSort(listToSort, pivot + 1, right);
}
}
And:
private int GetScoreFromLine(string[] lineToParce)
{
int length = lineToParce.Length;
return int.Parse(lineToParce[length - 1]);
}
Dont work, correctly.
Is there way to use ARRAY.SORT? Can anyone help. Thanks.
List<string[]>
sort without using LINQ I would imagine that's not so hard. – yamengameResults.OrderBy(x => int.Parse(x[x.Length - 1]))
– Frank