forked from ThatRendle/Simple.Data
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEnumerableExtensions.cs
More file actions
81 lines (72 loc) · 2.67 KB
/
EnumerableExtensions.cs
File metadata and controls
81 lines (72 loc) · 2.67 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
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
using System;
using System.Collections.Generic;
using System.Linq;
namespace Simple.Data.Extensions
{
public static class EnumerableExtensions
{
public static IDictionary<TKey,TValue> ToDictionary<TKey,TValue>(this IEnumerable<KeyValuePair<TKey,TValue>> source)
{
var dict = source as IDictionary<TKey, TValue>;
if (dict != null) return new Dictionary<TKey, TValue>(dict);
return source.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
}
public static IDictionary<TKey,TValue> ToDictionary<TKey,TValue>(this IEnumerable<KeyValuePair<TKey,TValue>> source, IEqualityComparer<TKey> equalityComparer)
{
var dict = source as IDictionary<TKey, TValue>;
if (dict != null) return new Dictionary<TKey, TValue>(dict);
return source.ToDictionary(kvp => kvp.Key, kvp => kvp.Value, equalityComparer);
}
public static IEnumerable<T> SkipLast<T>(this IEnumerable<T> source)
{
var buffer = default(T);
var enumerator = source.GetEnumerator();
if (enumerator.MoveNext())
{
buffer = enumerator.Current;
}
while (enumerator.MoveNext())
{
yield return buffer;
buffer = enumerator.Current;
}
}
public static IEnumerable<Tuple<T,T>> ToTuplePairs<T>(this IEnumerable<T> source)
{
var buffer = default(T);
var enumerator = source.GetEnumerator();
if (enumerator.MoveNext())
{
buffer = enumerator.Current;
}
while (enumerator.MoveNext())
{
yield return Tuple.Create(buffer, enumerator.Current);
buffer = enumerator.Current;
}
}
public static IEnumerable<T> ExtendInfinite<T>(this IEnumerable<T> source)
{
foreach (var item in source)
{
yield return item;
}
while (true)
{
yield return default(T);
}
}
public static IEnumerable<T> Replace<T>(this IEnumerable<T> source, T toReplace, T replaceWith)
{
return source.Select(item => Equals(item, toReplace) ? replaceWith : item);
}
public static IEnumerable<T> Append<T>(this IEnumerable<T> source, T item)
{
return source.Concat(Return(item));
}
public static IEnumerable<T> Return<T>(T item)
{
yield return item;
}
}
}