forked from ServiceStack/ServiceStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEnumerableExtensions.cs
More file actions
107 lines (93 loc) · 3.3 KB
/
EnumerableExtensions.cs
File metadata and controls
107 lines (93 loc) · 3.3 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
using System;
using System.Collections.Generic;
namespace ServiceStack.Common
{
public static class EnumerableExtensions
{
public static bool IsEmpty<T>(this ICollection<T> collection)
{
return collection == null || collection.Count == 0;
}
public static HashSet<T> ToHashSet<T>(this IEnumerable<T> items)
{
return new HashSet<T>(items);
}
public static List<To> SafeConvertAll<To, From>(this IEnumerable<From> items, Func<From, To> converter)
{
return items == null ? new List<To>() : Extensions.EnumerableExtensions.ConvertAll(items, converter);
}
public static List<object> ToObjects<T>(this IEnumerable<T> items)
{
var to = new List<object>();
foreach (var item in items)
{
to.Add(item);
}
return to;
}
public static string FirstNonDefaultOrEmpty(this IEnumerable<string> values)
{
foreach (var value in values)
{
if (!string.IsNullOrEmpty(value)) return value;
}
return null;
}
public static T FirstNonDefault<T>(this IEnumerable<T> values)
{
foreach (var value in values)
{
if (!Equals(value, default(T))) return value;
}
return default(T);
}
public static bool EquivalentTo<T>(this IEnumerable<T> thisList, IEnumerable<T> otherList)
{
if (thisList == null || otherList == null) return thisList == otherList;
var otherEnum = otherList.GetEnumerator();
foreach (var item in thisList)
{
if (!otherEnum.MoveNext()) return false;
var thisIsDefault = Equals(item, default(T));
var otherIsDefault = Equals(otherEnum.Current, default(T));
if (thisIsDefault || otherIsDefault)
{
return thisIsDefault && otherIsDefault;
}
if (!item.Equals(otherEnum.Current)) return false;
}
var hasNoMoreLeftAsWell = !otherEnum.MoveNext();
return hasNoMoreLeftAsWell;
}
public static IEnumerable<T[]> BatchesOf<T>(this IEnumerable<T> sequence, int batchSize)
{
var batch = new List<T>(batchSize);
foreach (var item in sequence)
{
batch.Add(item);
if (batch.Count >= batchSize)
{
yield return batch.ToArray();
batch.Clear();
}
}
if (batch.Count > 0)
{
yield return batch.ToArray();
batch.Clear();
}
}
public static Dictionary<TKey, T> ToSafeDictionary<T, TKey>(this IEnumerable<T> list, Func<T, TKey> expr)
{
var map = new Dictionary<TKey, T>();
if (list != null)
{
foreach (var item in list)
{
map[expr(item)] = item;
}
}
return map;
}
}
}