-
Notifications
You must be signed in to change notification settings - Fork 275
Expand file tree
/
Copy pathCollectionExtensions.cs
More file actions
50 lines (48 loc) · 1.69 KB
/
CollectionExtensions.cs
File metadata and controls
50 lines (48 loc) · 1.69 KB
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
using System;
using System.Collections.Generic;
using System.Linq;
namespace Microsoft.OpenApi
{
/// <summary>
/// Dictionary extension methods
/// </summary>
internal static class CollectionExtensions
{
/// <summary>
/// Returns a new dictionary with entries sorted by key using a custom comparer.
/// </summary>
internal static IDictionary<TKey, TValue> Sort<TKey, TValue>(
this IDictionary<TKey, TValue> source,
IComparer<TKey> comparer)
where TKey : notnull
{
#if NET7_0_OR_GREATER
ArgumentNullException.ThrowIfNull(nameof(source));
ArgumentNullException.ThrowIfNull(nameof(comparer));
#else
if (source == null)
throw new ArgumentNullException(nameof(source));
if (comparer == null)
throw new ArgumentNullException(nameof(comparer));
#endif
return source.OrderBy(kvp => kvp.Key, comparer)
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
}
/// <summary>
/// Sorts any IEnumerable<T> using the specified comparer and returns a List</T>.
/// </summary>
internal static List<T> Sort<T>(this IEnumerable<T> source, IComparer<T> comparer)
{
#if NET7_0_OR_GREATER
ArgumentNullException.ThrowIfNull(source);
ArgumentNullException.ThrowIfNull(comparer);
#else
if (source == null)
throw new ArgumentNullException(nameof(source));
if (comparer == null)
throw new ArgumentNullException(nameof(comparer));
#endif
return source.OrderBy(item => item, comparer).ToList();
}
}
}