我想对 List 进行排序,其中字符串数组的最后一个元素是排序键。我需要前 5 个结果。(低调)
这可行,但我不想使用 LINQ:
...
List<string[]> gameResults = OpenResults(fileLocation);
gameResults.Add(CurrentPlayerResult());
var newOrderedGameResults =
from line in currentGameResults
orderby int.Parse(line.LastOrDefault())
select line;
...
但这不会:
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);
}
在哪里:
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);
}
}
和:
private int GetScoreFromLine(string[] lineToParce)
{
int length = lineToParce.Length;
return int.Parse(lineToParce[length - 1]);
}
不工作,正确。
有没有办法使用 ARRAY.SORT? 任何人都可以帮忙。谢谢。