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
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
Sorts the elements in an entire
Array
using theIComparable
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 IComparableArray.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
{
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();