【问题标题】:Sort list of string arrays c#对字符串数组的排序列表c#
【发布时间】:2014-07-15 10:03:56
【问题描述】:

我有一个字符串数组列表,其中的数组格式为 [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# list sorting arrays


【解决方案1】:

您可以使用 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

【讨论】:

    【解决方案2】:

    你可以这样做:

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

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

    如果您的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"}
                                                };
    

    解决该问题的更好方法是使用自定义类,将TypeBreadName 作为属性,然后使用它而不是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&lt;Animal&gt; 像:

    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();
    

    如果你愿意,可以实现自己的自定义排序,见:How to use the IComparable and IComparer interfaces in Visual C#

    【讨论】:

    • 好的,我一定犯了一些可怕的错误,但请指出。
    • 这与我的答案相似,所以为什么我没有投票?我很震惊;)
    • @TimSchmelter,我在您回答 2 分钟后发布,但在发布之前我从未看到您的回答。我相信人们不喜欢重复的答案,重要的是你很受欢迎:P
    • @Habib:好吧,让我们直说吧。 +1。当然蒂姆也是;)
    • + 另一个 1 表示“更好的处理方法”。
    【解决方案3】:

    如果您可以使用 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();
    

    【讨论】:

      【解决方案4】:

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

      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

      【讨论】:

      • 我可以看到这个问题已有 6 年历史,并且已经有一个被认为是正确的答案。如果您知道如何从头开始实现搜索算法,它总是很有用的,所以做得很好。如果您正在尝试建立您的 StackOverflow 声誉分数,我建议您尝试查找您熟悉使用搜索工具的问题,或者使用“周”或“月”按钮查看较新的问题。只要有人喜欢或接受您的某个答案,您就会立即积累声望点和徽章。
      • 感谢马克的建设性建议!
      猜你喜欢
      • 2017-10-28
      • 2017-09-26
      • 2013-12-31
      • 2012-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多