Category Archives: C#

(C#) Swap two items in a generic list

Put this in a static class. This will apply to Lists of any type.

public static IList<T> Swap<T>(this IList<T> list, int indexA, int indexB)
{
	if (indexB > -1 && indexB < list.Count)
	{
		T tmp = list[indexA];
		list[indexA] = list[indexB];
		list[indexB] = tmp;
	}
	return list;
}

Simply call it like this

myList.Swap(indexA, indexB);

(C#) Sort lists

Lets say you have a list of person objects (List persons)

You may use Sort to update the existing list.

personsList.Sort((x, y) => string.Compare(x.Name, y.Name));

or OrderBy to produce a new, ordered list.

var newPersonsList = persons.OrderBy(x => x.Name);

(C#) Confirmation when closing a form

Add an event handler for Form Closing and use this code. This is a really simple solution.

private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
  if (MessageBox.Show("Are you sure?", "Close application", MessageBoxButtons.YesNo) == DialogResult.Yes)
     e.Cancel = false;
  else
     e.Cancel = true;
}