Sort list of string arrays c#

前端 未结 4 1266
野的像风
野的像风 2021-01-18 02:11

I have a list of string arrays, where the arrays are formatted as [Animal, Breed, Name]:

{ [\"Dog\", \"Golden Retriever\", \"Rex\"],
  [\"Cat\", \"Tabby\", \         


        
4条回答
  •  天涯浪人
    2021-01-18 02:41

    For a more simple or well-rounded approach, you could use bubble sort to sort your list of string arrays, depending on the element you wish to sort by. For example:

    static void Main(string[] args)
    {
        List animalCount = new List() 
        { 
            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 sortedAnimalCount = SortedCountList(animalCount);
    
        foreach (string[] item in sortedAnimalCount)
        {
            Console.WriteLine(item[0] + "" + item[1]);
        }
    
        Console.ReadKey();
    }
    
    static List SortedCountList(List 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();
    }
    
    • Outputs: Fish: 26 Monkeys: 15 Dogs: 12 Cats: 6 Elephants: 2 Dinosaurs: 0

提交回复
热议问题