Logo

Programming-Idioms

  • Erlang
  • Vb

Idiom #28 Sort by a property

Sort the elements of the list (or array-like collection) items in ascending order of x.p, where p is a field of the type Item of the objects in items.

Imports System.Linq
items.OrderBy(Function(x) x.p)

The LINQ-to-objects extension method OrderBy is available for all IEnumerable(Of T)
Imports System.Collections.Generic
System.Array.Sort(items, Comparer(Of Item).Create(Function(a, b) a.p - b.p))

Sorts the array items in-place.
	
sort_by_birth(ListOfMaps) ->
  lists:sort(
    fun(A, B) ->
      maps:get(birth, A, undefined) =< maps:get(birth, B, undefined)
    end, ListOfMaps).

sort_by_birth(ListOfRecords) -> lists:keysort(#item.birth, ListOfRecords).

First function works with a list of maps, like [#{birth => "1982-01-03"}, …].
Second function works with a list of records, like [#item{birth = "1982-01-03", …}, …]
with Ada.Containers.Vectors;
use Ada.Containers;
declare
   function Compare_Function (Left, Right : Item) return Boolean is (Left.P < Right.P);
   
   package Item_Vector_Sorting is new Item_Vectors.Generic_Sorting (Compare_Function);

   use Item_Vector_Sorting;
begin
   Sort (Items);
end;

New implementation...
< >
programming-idioms.org