-1

I Have an array like below code :

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

I want sort this array based on for example Title of Books. How do i it?

csharp net
  • 13
  • 7
  • As an aside, I would *strongly* recommend against using mutable structs and public fields. It looks like this should probably be a class with public *properties*... you should also look into .NET naming conventions. – Jon Skeet Jan 19 '16 at 16:45
  • Also after 7 years @JonSkeet no longer recommends duplicate http://stackoverflow.com/questions/1304278/how-to-sort-an-array-containing-class-objects-by-a-property-value-of-a-class-ins (but it still relevant). You can find that recommendation in [duplicate](http://stackoverflow.com/questions/1304278/how-to-sort-an-array-containing-class-objects-by-a-property-value-of-a-class-ins) that talks explicitly about arrays. – Alexei Levenkov Jan 19 '16 at 16:58

2 Answers2

0

You could use Array.Sort:

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

or LINQ:

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

The latter needs to recreate the array.

As an aside, use a class instead of a mutable struct.

Community
  • 1
  • 1
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
0

Use LINQ's OrderBy to sort the array:

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

Reference

Community
  • 1
  • 1
Shaharyar
  • 12,254
  • 4
  • 46
  • 66