C# Bool Sort Example

This C# example program displays the result of sorting bools. Bools are sorted from false to true by default.

Bool sort. Bools can be sorted.

When stored in an array or List, they can be ordered with Sort methods. This allows you to order your collection by true or false. This is useful for promoting or demoting elements programmatically.

 

 

Example. One use for sorting bools is reordering a List of file information structures. Sometimes, you need to mark some elements in the List as "bad," pushing them to the bottom of the List.

 

Tip: Bools have a default of false in a class or struct. With bools, the default Sort method will put false before true.

True, False

C# program that sorts bools

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
	List<bool> l = new List<bool>();
	l.Add(true);
	l.Add(false);
	l.Add(false);
	l.Add(false);
	l.Add(true);

	Console.WriteLine("Unsorted bools:");
	foreach (bool b in l)
	{
	    Console.WriteLine(b);
	}

	l.Sort();
	Console.WriteLine("Sorted bools:");
	foreach (bool b in l)
	{
	    Console.WriteLine(b);
	}

	var v = from b in l
		orderby b descending
		select b;
	Console.WriteLine("Reverse sorted bools:");
	foreach (bool b in v)
	{
	    Console.WriteLine(b);
	}
    }
}

Output

Unsorted bools:
True
False
False
False
True

Sorted bools:
False
False
False
True
True

Reverse sorted bools:
True
True
False
False
False

The example populates a List generic with 5 bool values. It displays the List in that state, and then sorts it with List.Sort method. The default Sort method orders the bools from False to True. This is just like ordering 0 to 1.

Finally: The descending keyword in the example above uses the LINQ query syntax, which is extremely useful for sorting.

 

Discussion. To filter, you can add a bool property or field to your class, and then in your algorithm assign that to true or false depending on whether you want to give the item priority. Use true to promote the class.

 

Then: Sort the objects with the LINQ query syntax above, using the orderby descending clause.

orderbyDescending

One algorithm this is useful for is a selection where only one element should be chosen, but no elements should be eliminated. Elsewhere in your algorithm, mark the elements as good or bad with the bool.

Finally: You can select the elements using a test, starting with the elements not marked as "bad."

Tip: This improves error handling as it doesn't actually eliminate any elements from consideration.

 

Summary. Bools are sorted from false to true. The descending sort will order them from true to false. True is essentially equal to 1, and false to 0. Use boolean sorting for selection algorithms where some objects should be demoted.