Logo

Programming-Idioms

  • Scheme
  • Ruby
  • VB
  • C#

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.

using System.Linq;
items.OrderBy(x => x.p)

The LINQ-to-objects extension method OrderBy is available for all IEnumerable<T>
using System.Collections.Generic;
System.Array.Sort(items, Comparer<Item>.Create((a, b) => a.p - b.p));

Sorts the array items in-place.
(define-struct item (p x y) #:transparent)
(define items (list (item 1 2 3) (item 0 0 0) (item 5 2 1)))
(sort items < #:key item-p)

< is the integer comparison function. There is also string<?.
items.sort_by(&:p)
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.
Imports System.Linq
items.OrderBy(Function(x) x.p)

The LINQ-to-objects extension method OrderBy is available for all IEnumerable(Of T)
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