本文介绍了字符串数组排序列表C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字符串数组列表,其中这些数组的格式设置为[动物,品种,名称]:
I have a list of string arrays, where the arrays are formatted as [Animal, Breed, Name]:
{ ["Dog", "Golden Retriever", "Rex"],
["Cat", "Tabby", "Boblawblah"],
["Fish", "Clown", "Nemo"],
["Dog", "Pug", "Daisy"],
["Cat", "Siemese", "Wednesday"],
["Fish", "Gold", "Alaska"]
}
我将如何对这个列表进行排序,以便按照动物"(Animal)和品种"(Breed)的字母顺序进行排列?即:
How would I sort this list so that it was arranged alphabetically by "Animal", and then "Breed"? i.e.:
{ ["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]));
但是,这不能正确地对第二列进行排序.除了按字母顺序对前两列进行排序外,我还应如何在第三列中添加?
But that is not sorting the second column correctly. In addition to sorting by the first two columns alphabetically, how would I then add in the third column?
推荐答案
您可以使用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
这篇关于字符串数组排序列表C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!