-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSortedList.cs
86 lines (74 loc) · 3.53 KB
/
SortedList.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
using System;
using System.Collections.Generic;
namespace ABCNET.Utils
{
/// <summary>
/// Предоставляет функционал для работы с отсортированными списками.
/// </summary>
public static class SortedList
{
#region public
/// <summary>
/// Создаёт отсортированный список из указанных значений.
/// </summary>
/// <param name="values">Значения.</param>
/// <returns>Отсортированный список.</returns>
public static SortedList<TKey, TValue> Of<TKey, TValue>(params KeyValuePair<TKey, TValue>[] values)
{
if (values is null)
throw new ArgumentNullException(nameof(values));
SortedList<TKey, TValue> result = new SortedList<TKey, TValue>();
foreach (var item in values)
result.Add(item.Key, item.Value);
return result;
}
/// <summary>
/// Создаёт отсортированный список на основе функции селектора.
/// </summary>
/// <param name="count">Количество элементов.</param>
/// <param name="selector">Функция селектор.</param>
/// <param name="firstIndex">Начальный индекс.</param>
/// <returns>Отсортированный список.</returns>
public static SortedList<TKey, TValue> By<TKey, TValue>(int count, Func<int, KeyValuePair<TKey, TValue>> selector, int firstIndex = 0)
{
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count));
if (selector is null)
throw new ArgumentNullException(nameof(selector));
SortedList<TKey, TValue> result = new SortedList<TKey, TValue>();
for (int i = 0; i < count; i++)
{
KeyValuePair<TKey, TValue> keyValuePair = selector(i + firstIndex);
result.Add(keyValuePair.Key, keyValuePair.Value);
}
return result;
}
/// <summary>
/// Создаёт отсортированный список на основе функции селектора.
/// </summary>
/// <param name="count">Количество элементов.</param>
/// <param name="first">Первый элемент.</param>
/// <param name="next">Функция получения следующего элемента.</param>
/// <returns>Отсортированный список.</returns>
public static SortedList<TKey, TValue> By<TKey, TValue>(int count, KeyValuePair<TKey, TValue> first, Func<KeyValuePair<TKey, TValue>, KeyValuePair<TKey, TValue>> next)
{
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count));
if (next is null)
throw new ArgumentNullException(nameof(next));
SortedList<TKey, TValue> result = new SortedList<TKey, TValue>
{
{ first.Key, first.Value }
};
KeyValuePair<TKey, TValue> previous = first;
for (int i = 1; i < count; i++)
{
KeyValuePair<TKey, TValue> keyValuePair = next(previous);
result.Add(keyValuePair.Key, keyValuePair.Value);
previous = keyValuePair;
}
return result;
}
#endregion public
}
}