C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: Bools have a default of false in a class or struct. With bools, the default Sort method will put false before true.
True, FalseInfo: 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.
Default order: The default Sort method orders the bools from False to True. This is just like ordering 0 to 1.
Descending: The descending keyword in the example above uses the LINQ query syntax, which is useful for sorting.
LINQC# program that sorts bools
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
var items = new List<bool>();
items.Add(true);
items.Add(false);
items.Add(false);
items.Add(false);
items.Add(true);
foreach (bool value in items)
{
Console.WriteLine("UNSORTED: {0}", value);
}
// Sort.
items.Sort();
foreach (bool value in items)
{
Console.WriteLine("SORTED: {0}", value);
}
// Sort descending.
var sorted = from item in items
orderby item descending
select item;
foreach (bool value in sorted)
{
Console.WriteLine("REVERSE SORTED: {0}", value);
}
}
}
Output
UNSORTED: True
UNSORTED: False
UNSORTED: False
UNSORTED: False
UNSORTED: True
SORTED: False
SORTED: False
SORTED: False
SORTED: True
SORTED: True
REVERSE SORTED: True
REVERSE SORTED: True
REVERSE SORTED: False
REVERSE SORTED: False
REVERSE SORTED: False
Here: We create a List of TestData items. We then sort them with the IsImportant property—important items come before unimportant ones.
Info: This approach can improve error handling as it does not eliminate any elements from consideration.
Exit: We can exit the foreach-loop with a break or return when we find an item that matches our conditions.
ForeachC# program that uses bool property sort
using System;
using System.Collections.Generic;
using System.Linq;
class TestData
{
public bool IsImportant { get; set; }
public string Data { get; set; }
}
class Program
{
static void Main()
{
// Add data to the list.
var items = new List<TestData>();
items.Add(new TestData() { IsImportant = true, Data = "Bird" });
items.Add(new TestData() { IsImportant = false, Data = "Cat" });
items.Add(new TestData() { IsImportant = true, Data = "Human" });
// Sort by bool on class.
var sorted = from item in items
orderby item.IsImportant descending
select item;
// Put "important" items first.
foreach (var item in sorted)
{
Console.WriteLine("ITEM: " + item.IsImportant + "; " + item.Data);
}
}
}
Output
ITEM: True; Bird
ITEM: True; Human
ITEM: False; Cat
So: Use true to promote the class. Sort the objects with the LINQ query syntax, using the orderby descending clause.
orderby