如何根据特定索引对数组进行排序

时间:2016-01-19 16:40:37

标签: c# arrays

我有一个如下代码的数组:

    struct Book_Struct
    {
        public string Title;
        public string Auther;
        public int Date;
        public int ID;
    }

    static void Print(Book_Struct[] a, int b)
    {
        for (int i = 0; i < b; i++)
        {
            Console.WriteLine("  Name of Book " + (i + 1) + " is : " + "\" " + a[i].Title + " \"");
            Console.WriteLine("Auther of Book " + (i + 1) + " is : " + "\" " + a[i].Auther + " \"");
            Console.WriteLine("  Date of Book " + (i + 1) + " is : " + "\" " + a[i].Date + " \"");
            Console.WriteLine("    ID of Book " + (i + 1) + " is : " + "\" " + a[i].ID + " \"");
            Console.WriteLine("\n---------------------------------\n");
        }
    } 

我希望根据例如书籍标题对此数组进行排序。我怎么了?

2 个答案:

答案 0 :(得分:0)

您可以使用Array.Sort

Array.Sort(a, (b1, b2) => b1.Title.CompareTo(b2.Title));

或LINQ:

a = a.OrderBy(book => book.Title).ToArray();

后者需要重新创建数组。

顺便说一句,请使用课程而不是mutable struct.

答案 1 :(得分:0)

使用LINQ&#39; OrderBy对数组进行排序:

a = a.OrderBy(x => x.Title).ToArray();

Reference