Sorting a string array in lexicographical order using LINQ and Lambda expression
I think I wrote a function in C for this purpose back in school days. I needed this again in one of my projects recently and for a couple of seconds I thought of a C# – port of that code before I’d realized that LINQ and Lambda expression could come to my rescue. And all it took is mere 4 lines of code (if you count the string array declaration line in the sole purpose
)
Oh, and you must add the System.Linq namespace.
string[] strArr = new string[] { "Gibbs", "Ntini", "Pollock", "Cronje", "Smith", "Kirsten", "Steyn", };
List list = strArr.ToList();
list.Sort((str1, str2) => str1.CompareTo(str2));
strArr = list.ToArray();
After the sort the array looks like this:
{ "Cronje", "Gibbs", "Kirsten", "Ntini", "Pollock", "Smith", "Steyn" }
Posted: April 19th, 2010
at 2:42am by Kayes
Tagged with alphabetic sort, C#, dictionary sort, lambda expression, lexicographical sort, linq
Categories: C#
Comments: No comments
Using Enumeration types in switch-case block and ComboBox in C#
Here’s a code snippet that demonstrates how to use enum types in a switch-case block in combination with the ComboBox control. Just wanted to share ’cause I had to look it up on the web. Hope it helps somebody.
using System;
using System.Windows.Forms;
using System.Diagnostics;
namespace EnumWithCombo
{
public partial class PlayerSelectionForm : Form
{
private enum Players
{
Gibbs, Richards, Cronje, Kirsten, Kallis, Smith, Villiers, Pollock, Ntini, Klusener, Steyn, Rhodes, Bosman, Kemp, Botha, Harris, Roelof
}
private string url = "http://www.cricinfo.com/ci/content/player/45224.html";
public PlayerSelectionForm()
{
InitializeComponent();
playersComboBox.DataSource = Enum.GetValues(typeof(Players));
}
private void submitButton_Click(object sender, EventArgs e)
{
switch ((Players) playersComboBox.SelectedItem)
{
case Players.Gibbs:
Process.Start(new ProcessStartInfo("iexplore", url));
break;
default:
MessageBox.Show(((Players) playersComboBox.SelectedItem).ToString());
break;
}
}
}
}
