Skip to content

PriorityEnumerable.OrderByPriority(params[] priorities)

kurnakovv edited this page Feb 19, 2024 · 1 revision

Description

Order source by priorities

Uses this method internally.

Signature

IOrderedEnumerable<TSource> OrderByPriority<TSource, TKey>(
    this IEnumerable<TSource> source,
    Func<TSource, TKey> keySelector,
    IEnumerable<TKey> priorities
)

Use cases

  • New IOrderedEnumerable<TSource> with elements ordered by priorities when source, keySelector, priorities is correct.
  • ArgumentNullException when source or keySelector or priorities is null.
  • ArgumentException when priorities contain duplicate values.

Type Parameters

TSource - source type. TKey - The type of the key returned by keySelector

Parameters

source - A sequence of values to order. keySelector - A function to extract a key from an element. priorities - Elements that determine the order of enumerable.

Returns

New ordered enumerable by priorities.

Code examples

String's

// Simple code example
var types = new string[] { "SUPER LOW", "LOW", "HIGH", "SUPER SUPER LOW", "MEDIUM" };
var output = types.OrderByPriority(x => x, new string[] { "HIGH", "MEDIUM", "LOW" }).ToArray();
// output: "HIGH", "MEDIUM", "LOW", "SUPER LOW", "SUPER SUPER LOW"

String property

public class Driver
{
    public string Name { get; set; }
    public string Category { get; set; }
}

IEnumerable<Driver> source = new List<Driver>
{
    new Driver() { Name = "Bob", Category = "Second category" },
    new Driver() { Name = "Huxley", Category = "First category" },
    new Driver() { Name = "Tom", Category = "Third category" },
    new Driver() { Name = "Sutton", Category = "Third category" },
    new Driver() { Name = "Lev", Category = "First category"  },
    new Driver() { Name = "Max", Category = "Second category" },
    new Driver() { Name = "Willow", Category = "None" },
    new Driver() { Name = "Jack", Category = "Third category" },
    new Driver() { Name = "Ruby", Category = "Second category" },
    new Driver() { Name = "Willow", Category = "First category"  },
};

var result = source.OrderByPriority(x => x.Category, "First category", "Second category", "Third category").ToList();

// result:
Name: 'Huxley', Category: 'First category'
Name: 'Lev', Category: 'First category'
Name: 'Willow', Category: 'First category'
Name: 'Bob', Category: 'Second category'
Name: 'Max', Category: 'Second category'
Name: 'Ruby', Category: 'Second category'
Name: 'Tom', Category: 'Third category'
Name: 'Sutton', Category: 'Third category'
Name: 'Jack', Category: 'Third category'
Name: 'Willow', Category: 'None'

You can also do this with another types, for example enum, int, etc...

More code examples here