-
Notifications
You must be signed in to change notification settings - Fork 0
/
KeyValuePair.cs
60 lines (55 loc) · 1.99 KB
/
KeyValuePair.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
using System;
using System.Collections.Generic;
using System.Linq;
namespace Recore.Linq
{
public static partial class Renumerable
{
/// <summary>
/// Creates a <see cref="Dictionary{TKey, TValue}"/> from a sequence of key-value pairs.
/// </summary>
public static Dictionary<TKey, TValue> ToDictionary<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> source)
where TKey : notnull
=> source.ToDictionary(x => x.Key, x => x.Value);
/// <summary>
/// Projects each key in a sequence of key-value pairs to a new form.
/// </summary>
public static IEnumerable<KeyValuePair<TResult, TValue>> OnKeys<TKey, TValue, TResult>(
this IEnumerable<KeyValuePair<TKey, TValue>> source,
Func<TKey, TResult> func)
where TResult : notnull
{
if (source is null)
{
throw new ArgumentNullException(nameof(source));
}
if (func is null)
{
throw new ArgumentNullException(nameof(source));
}
return source
.Select(kvp => KeyValuePair.Create(func(kvp.Key), kvp.Value))
.ToDictionary();
}
/// <summary>
/// Projects each value in a sequence of key-value pairs to a new form.
/// </summary>
public static IEnumerable<KeyValuePair<TKey, TResult>> OnValues<TKey, TValue, TResult>(
this IEnumerable<KeyValuePair<TKey, TValue>> source,
Func<TValue, TResult> func)
where TKey : notnull
{
if (source is null)
{
throw new ArgumentNullException(nameof(source));
}
if (func is null)
{
throw new ArgumentNullException(nameof(source));
}
return source
.Select(kvp => KeyValuePair.Create(kvp.Key, func(kvp.Value)))
.ToDictionary();
}
}
}