如何在 C# 中按字母顺序对列表<字符[]>进行排序?



我有一个字符串列表,我使用以下方法对它们进行排序:

if (SortedList[x].str[p].CompareTo(SortedList[x + 1].str[p]) > 0) //Sort the list
{
Data aux = SortedList[x];
SortedList[x] = SortedList[x + 1];
SortedList[x + 1] = aux;
}

str是字符串列表,但我必须将该列表转换为List<char[]>,现在我无法使用str.CompareTo()方法,因为这仅适用于字符串......

我正在考虑创建一个字符串列表,将char[]转换为string并使用我正在使用的CompareTo()方法对其进行排序,然后通过转换排序的字符串列表来创建另一个List<char[]>

有没有更有效的方法来对List<char[]>进行排序?

你试过使用 LINQ 吗?

using System;
using System.Collections.Generic;
using System.Linq;
public class Program
{
public static void Main()
{
var charList = new List<char[]>();
// Initialize list of char array
char[] array1 = { 's', 'a', 'm' };
char[] array2 = { 's', 'm', 'i', 't', 'h' };
char[] array3 = { 'c', 'o', 'o', 'l'};
// Add them
charList.Add(array1);
charList.Add(array2);
charList.Add(array3);
Console.WriteLine("--Before sorting--");
foreach (char[] item in charList) {
Console.WriteLine(item);
}
// Sorting
charList = charList.OrderBy(a => new string(a)).ToList();

Console.WriteLine("--After sorting--");
foreach (char[] item in charList) {
Console.WriteLine(item);
}
}
}

输出:

--Before sorting--
sam
smith
cool
--After sorting--
cool
sam
smith

在这里测试:https://dotnetfiddle.net/wcYSAE

编辑:虽然根据您的问题我不清楚,但通常当我必须对列表进行排序时,我更喜欢使用 C# 提供的功能而不是重新发明轮子。 关于性能,其他C#大师可以为我们解答。

为什么不直接使用 Sort?正如奥米内所提到的

// Declare Sentence Variable
string sentence = "The quick brown fox jumps over the lazy dog";
// Initialize New List of type char
List<char> charList = new List<char>();
// Remove Spaces and Lowercase all Letters and Add to List
charList.AddRange(sentence.Replace(" ", string.Empty).ToLower());
// Sort List<char>()
charList.Sort();
// Output Statements
Console.WriteLine($"Before: {sentence}");
Console.WriteLine($"After: {new string(charList.ToArray())}");

输出:

Before: The quick brown fox jumps over the lazy dog
After: abcdeeefghhijklmnoooopqrrsttuuvwxyz

最新更新