Repository navigation
PriorityEnumerable.OrderByPriority(IEnumerable priorities)
kurnakovv edited this page Feb 17, 2024
·
5 revisions
Order source by priorities
IOrderedEnumerable<TSource> OrderByPriority<TSource, TKey>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
IEnumerable<TKey> priorities
)- New
IOrderedEnumerable<TSource>with elements ordered byprioritieswhensource,keySelector,prioritiesis correct. -
ArgumentNullExceptionwhensourceorkeySelectororprioritiesis null. -
ArgumentExceptionwhenprioritiescontain duplicate values.
TSource - source type.
TKey - The type of the key returned by keySelector
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.
New ordered enumerable by priorities.
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" },
};
IEnumerable<string> priorities = new List<string>()
{
"First category",
"Second category",
"Third category"
};
var result = source.OrderByPriority(x => x.Category, priorities).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