排序字符串数组列表c#

本文关键字:列表 数组 字符串 排序 | 更新日期: 2023-09-27 18:05:26

我有一个字符串数组列表,其中数组的格式为[Animal, Breed, Name]:

{ ["Dog", "Golden Retriever", "Rex"],
  ["Cat", "Tabby", "Boblawblah"],
  ["Fish", "Clown", "Nemo"],
  ["Dog", "Pug", "Daisy"],
  ["Cat", "Siemese", "Wednesday"],
  ["Fish", "Gold", "Alaska"]
}

我该如何排序这个列表,使它按照"动物"的字母顺序排列,然后是"品种"?例如:

{ ["Cat", "Siamese", "Boblawblah"],
  ["Cat", "Tabby", "Wednesday"],
  ["Dog", "Golden Retriever", "Rex"],
  ["Dog", "Pug", "Daisy"],
  ["Fish", "Clown", "Nemo"],
  ["Fish", "Gold", "Alaska"]
}

我正在尝试:

animalList.Sort((s, t) => String.Compare(s[0], t[0]));

但是这并没有正确排序第二列。除了按字母顺序对前两列进行排序之外,如何添加第三列呢?

排序字符串数组列表c#

您可以使用LINQ:

animalList = animalList
    .OrderBy(arr => arr[0])
    .ThenBy(arr  => arr[1])
    .ToList();

你的样品:

List<string[]> animalList = new List<String[]>{ 
            new []{"Dog", "Golden Retriever", "Rex"},
            new []{"Cat", "Tabby", "Boblawblah"},
            new []{"Fish", "Clown", "Nemo"},
            new []{"Dog", "Pug", "Daisy"},
            new []{"Cat", "Siemese", "Wednesday"},
            new []{"Fish", "Gold", "Alaska"}
        };
结果:

-       [0] {string[3]} string[]
        [0] "Cat"   string
        [1] "Siemese"   string
        [2] "Wednesday" string
-       [1] {string[3]} string[]
        [0] "Cat"   string
        [1] "Tabby" string
        [2] "Boblawblah"    string
-       [2] {string[3]} string[]
        [0] "Dog"   string
        [1] "Golden Retriever"  string
        [2] "Rex"   string
-       [3] {string[3]} string[]
        [0] "Dog"   string
        [1] "Pug"   string
        [2] "Daisy" string
-       [4] {string[3]} string[]
        [0] "Fish"  string
        [1] "Clown" string
        [2] "Nemo"  string
-       [5] {string[3]} string[]
        [0] "Fish"  string
        [1] "Gold"  string
        [2] "Alaska"    string

你可以这样做:

var newList = list.OrderBy(r => r[0])
                  .ThenBy(r => r[1])
                  .ThenBy(r => r[2])
                  .ToList();

这将假设您的List将具有长度为至少 3项的字符串数组元素。这将首先根据数组的第一项Animal,然后是Bread,然后是Name对List进行排序。

如果您的List定义为:

List<string[]> list = new List<string[]> { new [] {"Dog", "Golden Retriever", "Rex"},
                                           new [] { "Cat", "Tabby", "Boblawblah"},
                                           new [] {"Fish", "Clown", "Nemo"},
                                           new [] {"Dog", "Pug", "Daisy"},
                                           new [] {"Cat", "Siemese", "Wednesday"},
                                           new [] {"Fish", "Gold", "Alaska"}
                                            };

解决这个问题的一个更好的方法是使用自定义类,Type, BreadName作为属性,然后使用它来代替string[]

你可以定义自己的类:

public class Animal
{
    public string Type { get; set; }
    public string Bread { get; set; }
    public string Name { get; set; }
    public Animal(string Type, string Bread, string Name)
    {
        this.Type = Type;
        this.Bread = Bread;
        this.Name = Name;
    }
}

,然后定义你的List<Animal>,像

List<Animal> animalList = new List<Animal>
{
    new Animal("Dog", "Golden Retriever", "Rex"),
    new Animal("Cat", "Tabby", "Boblawblah"),
    new Animal("Fish", "Clown", "Nemo"),
    new Animal("Dog", "Pug", "Daisy"),
    new Animal("Cat", "Siemese", "Wednesday"),
    new Animal("Fish", "Gold", "Alaska"),
};

之后你可以得到排序列表:

List<Animal> sortedList = animalList
                            .OrderBy(r => r.Type)
                            .ThenBy(r => r.Bread)
                            .ToList();

如果你愿意,你可以实现你自己的自定义排序,参见:如何在Visual c#中使用IComparable和IComparer接口

对于更简单或更全面的方法,可以使用冒泡排序对字符串数组列表进行排序,具体取决于希望排序的元素。例如:

static void Main(string[] args)
{
    List<string[]> animalCount = new List<string[]>() 
    { 
        new string[] { "Dogs: ", "12" }, 
        new string[] { "Cats: ", "6" }, 
        new string[] { "Monkeys: ", "15" },
        new string[] { "Fish: ", "26" },
        new string[] { "Dinosaurs: ", "0" },
        new string[] { "Elephants: ", "2" }
    };
    List<string[]> sortedAnimalCount = SortedCountList(animalCount);
    foreach (string[] item in sortedAnimalCount)
    {
        Console.WriteLine(item[0] + "" + item[1]);
    }
    Console.ReadKey();
}
static List<string[]> SortedCountList(List<string[]> countList)
{
    string[][] charArray = countList.ToArray();
    int ItemToSortBy = 1; // Sorts list depending on item 2 of each string array
    int numItems = charArray.Length;
    bool IsSwapping = true;
    int i = 0;
    while (i < (numItems - 1) && IsSwapping == true)
    {
        IsSwapping = false;
        for (int j = 0; j < numItems - i - 1; j++) // Bubble sort the List in reverse
        {
            if (Convert.ToInt32(charArray[j][ItemToSortBy]) < Convert.ToInt32(charArray[j + 1][ItemToSortBy]))
            {
                string[] temp = charArray[j];
                charArray[j] = charArray[j + 1];
                charArray[j + 1] = temp;
                IsSwapping = true;
            }
        }
        i += 1;
    }
    return charArray.ToList();
}
  • 输出:鱼:26猴子:15狗:12猫:6大象:2恐龙:0

如果你可以使用LINQ,你可以这样做:

myanimals = myanimals.OrderBy(a => a[0]).ThenBy(a => a[1]).ToList();

或相同的查询:

myanimals = (from a in animals order by a[0], a[1] select a).ToList();