Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting an array alphabetically in C#

Tags:

arrays

c#

sorting

Hope someone can help. I have created a variable length array that will accept several name inputs. I now want to sort the array in alphabetical order and return that to the console screen.

I thought that Array.Sort(names); would do this for me but I am getting an exception thrown. I have been looking at notes, examples and on-line but nothing seems to match what I am doing.

I have done the below so far. I am close to tearing my hair out here! PS I have been trying to figure this out for hours and I am 30+ years old trying to learn myself, so please don't just say "Do your homework" I have tried to resolve this and can not so I need someone to explain where I am going wrong. It is a Sunday and I am trying to do extra work and have no notes to cover this exactly

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Student_Array
{
    class Program
    {
        struct Student
        {
            public string Name;
        }

        static void Main(string[] args)
        {
            int numberOfStudents;
            Student[] names;
            string input;

            Console.WriteLine("How many students are there?");
            input = Console.ReadLine();
            numberOfStudents = int.Parse(input);

            names = new Student[numberOfStudents];


            for (int i = 0; i < names.Length; i++)
            {
                Student s;
                Console.WriteLine("Please enter student {0}'s name", (i + 1));
                s.Name = Console.ReadLine();
                names[i] = s;
            }
            ***Array.Sort<Student>(names);***
            for (int i = 0; i < names.Length; i++)
            {

                Console.WriteLine(names[i].Name);
            }
        }
    }
}
like image 851
user001 Avatar asked May 19 '13 15:05

user001


People also ask

How do you sort an array by name?

Given an array of strings in which all characters are of the same case, write a C function to sort them alphabetically. The idea is to use qsort() in C and write a comparison function that uses strcmp() to compare two strings.

How do you put letters in alphabetical order in C?

Master C and Embedded C Programming- Learn as you go User has to enter number of names, and those names are required to be sorted in alphabetical order with the help of strcpy() function. An array of characters (or) collection of characters is called a string.


2 Answers

This shall do the trick

Array.Sort(names, (x,y) => String.Compare(x.Name, y.Name));
like image 115
oleksii Avatar answered Sep 28 '22 10:09

oleksii


Your issue here might be that you are confusing the notions of students and names. By defining the Student struct, you are creating an entity that can represent more than a mere name. You could, for example, extend it to include Age, Hometown, and so forth. (For this reason, it might be more meaningful to name your array students rather than names.)

struct Student
{
    public string Name;
    public int Age;
    public string Hometown;
}

Given the possibility of multiple fields, the Array.Sort method needs to know what you want to sort your list upon. Do you want students ordered by name, by age, or by hometown?

Per the MSDN documentation on Array.Sort<T>:

Sorts the elements in an entire Array using the IComparable<T> generic interface implementation of each element of the Array.

This means that the type you are attempting to sort – in your case, Student – must implement the IComparable<T> interface, in order for the Array.Sort implementation to know how it should compare two Student instances. If you're convinced that students will always be sorted by name, you could implement it like so:

struct Student : IComparable<Student>
{
    public string Name;
    public int Age;
    public string Hometown;

    public int CompareTo(Student other)
    {
        return String.Compare(this.Name, other.Name);
    }
}

Alternatively, you could provide a function that extracts the sort key to the sort method itself. The easiest way of achieving this is through the LINQ OrderBy method:

names = names.OrderBy(s => s.Name).ToArray();
like image 43
Douglas Avatar answered Sep 28 '22 08:09

Douglas