排序字符串数组列表c#

时间:2014-05-26 15:27:32

标签: c# list sorting arrays

我有一个字符串数组列表,其中数组的格式为[Animal,Breed,Name]:

{ ["Dog", "Golden Retriever", "Rex"],
  ["Cat", "Tabby", "Boblawblah"],
  ["Fish", "Clown", "Nemo"],
  ["Dog", "Pug", "Daisy"],
  ["Cat", "Siemese", "Wednesday"],
  ["Fish", "Gold", "Alaska"]
}

我如何对此列表进行排序,以便按字母顺序排列" Animal",然后" Breed"?即:

{ ["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]));

但这并没有正确排序第二列。除了按字母顺序按前两列排序外,我如何在第三列中添加?

4 个答案:

答案 0 :(得分:10)

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

答案 1 :(得分:5)

你可以这样做:

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<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#

答案 2 :(得分:0)

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

答案 3 :(得分:0)

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

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