Saúl Castillo Saúl Castillo - 1 month ago 4
C# Question

Need some help sorting an array of structures in c#

Hello I would Like to receive some help. I have this structure:

struct data
{
public String names;
public int number;

}


I've been asked to show this structure in the console sorted alphabetically (by evaluating the names) I don't really know how to do this, I know how to sort arrays but i don't know how to sort a structure like this.

I am a beginner, any help is received thanks.

Answer

this might do the trick for you

data[] datas = new[] { 
     new data() { names = "Mohit", number = 3 },
     //More data like that
}

and then

Array.Sort<data>(datas, (x,y) => x.names.CompareTo(y.names));
//or
Array.Sort(datas, (x,y) => string.Compare(x.names, y.names));

Or by using System.Linq

datas.OrderBy(x=>x.names);