Sort list of string arrays c#

前端 未结 4 1265
野的像风
野的像风 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:24

    You can do:

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

    This will assume that your List will have an element of string array with a length of at least 3 items. This will first sort the List based on First item of the array, Animal, Then Bread and then Name.

    If your List is defined as:

    List list = new List { 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"}
                                                };
    

    A better way to approach that problem would be to have custom class, with Type, Bread and Name as property and then use that instead of string[]

    You can define your own class:

    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;
        }
    }
    

    and then define your List like:

    List animalList = new List
    {
        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"),
    };
    

    Later you can get the sorted list like:

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

    If you want, you can implement your own custom sorting, see: How to use the IComparable and IComparer interfaces in Visual C#

提交回复
热议问题