break

Sort an array of strings in C#

The task: You have a string that is comma delimited , and you would like to sort that string and display it in a listbox.

I am using ASP.NET to do this:

Default.aspx

<form id=”form1″ runat=”server”>
<asp:listbox id=”ListBox1″ runat=”server”></asp:listbox>
</form>

I just declare a listbox inside the form.

Default.aspx.cs

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// the comma delimited list
string names = "Lesseps,Daniel,Isaacs,Diaz";
// split the string and make it an array of strings
string[] listOfNames = names.Split(new char[] { ',' });
// sort the array of strings
Array.Sort(listOfNames);
foreach (string name in listOfNames)
{
ListBox1.Items.Add(name);
}
}
}

The result:
sort an array of strings

In C#, it is extremely easy to sort an array of strings, just use:

Array.Sort(listOfNames);

where listOfNames is an array of strings.

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.

CAPTCHA Image
Reload Image