0

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?

2
  • 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. Commented Jan 19, 2016 at 16:45
  • Also after 7 years @JonSkeet no longer recommends duplicate stackoverflow.com/questions/1304278/… (but it still relevant). You can find that recommendation in duplicate that talks explicitly about arrays. Commented Jan 19, 2016 at 16:58

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Use LINQ's OrderBy to sort the array:

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

Reference

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.