你可以这样做:
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"}
};
解决该问题的更好方法是使用自定义类,将Type、Bread 和Name 作为属性,然后使用它而不是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();
如果你愿意,可以实现自己的自定义排序,见:How to use the IComparable and IComparer interfaces in Visual C#