-
Notifications
You must be signed in to change notification settings - Fork 0
/
Util.cs
354 lines (291 loc) · 13.2 KB
/
Util.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace dotnet_tools
{
/// <summary>
/// A collection of useful methods.
/// </summary>
public static class Util
{
#region Enum Extensions
/// <summary>
/// Returns the number of the constants in a specified enumeration, including repetitions of the same values if any exist.
/// </summary>
public static int Count<TEnum>() where TEnum : Enum => Values<TEnum>().Length;
/// <summary>
/// Returns the number of the constants in a specified enumeration, including repetitions of the same values if any exist.
/// </summary>
public static int Count<TEnum>(this TEnum @enum) where TEnum : Enum => Count<TEnum>();
/// <summary>
/// Returns the values of the constants in a specified enumeration, including repetitions of the same values if any exist.
/// </summary>
public static Array Values<TEnum>() where TEnum : Enum => Enum.GetValues(typeof(TEnum));
/// <summary>
/// Returns the values of the constants in a specified enumeration, including repetitions of the same values if any exist.
/// </summary>
public static Array Values<TEnum>(this TEnum @enum) where TEnum : Enum => Values<TEnum>();
/// <summary>
/// Returns the names of the constants in a specified enumeration.
/// </summary>
public static string[] Names<TEnum>() where TEnum : Enum => Enum.GetNames(typeof(TEnum));
/// <summary>
/// Returns the names of the constants in a specified enumeration.
/// </summary>
public static string[] Names<TEnum>(this TEnum @enum) where TEnum : Enum => Names<TEnum>();
/// <summary>
/// Returns the number of the constants in a specified enumeration, including repetitions of the same values if any exist.
/// </summary>
public static int Count(this Enum @enum) => @enum.Values().Length;
/// <summary>
/// Returns the values of the constants in a specified enumeration, including repetitions of the same values if any exist.
/// </summary>
public static Array Values(this Enum @enum) => @enum.GetType().GetEnumValues();
/// <summary>
/// Returns the names of the constants in a specified enumeration.
/// </summary>
public static string[] Names(this Enum @enum) => @enum.GetType().GetEnumNames();
#endregion
/// <summary>
/// Checks whether <paramref name="obj"/> is in the closed (including bounds) range [<paramref name="min"/>, <paramref name="max"/>].
/// </summary>
///
/// <typeparam name="T">
/// The type of this object and the arguments.
/// </typeparam>
///
/// <param name="obj">The instance to be checked.</param>
/// <param name="min">The range' lower bound.</param>
/// <param name="max">The range' upper bound. Must be <b>greater than or equal to</b> <paramref name="min"/>.</param>
///
/// <returns>
/// <see langword="true"/> if <paramref name="obj"/>'s value is in the range as specified; otherwise, <see langword="false"/>.
/// </returns>
///
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown when <paramref name="min"/> is greater than <paramref name="max"/>.
/// </exception>
public static bool InRange<T>(this T obj, in T min, in T max) where T : IComparable
{
if (min.CompareTo(max) > 0)
throw new ArgumentOutOfRangeException("min should not be greater than max");
return obj.CompareTo(min) >= 0 && obj.CompareTo(max) <= 0;
}
/// <summary>
/// Checks whether <paramref name="obj"/> is in the range [<paramref name="min"/>, <paramref name="max"/>);
/// that is: including <paramref name="min"/> and <b>not</b> including <paramref name="max"/>.
/// </summary>
///
/// <typeparam name="T">
/// The type of this object and the arguments.
/// </typeparam>
///
/// <param name="obj">The instance to be checked.</param>
/// <param name="min">The range' lower (inclusive) bound.</param>
/// <param name="max">The range' upper (exclusive) bound. Must be <b>greater than</b> <paramref name="min"/>.</param>
///
/// <returns>
/// <see langword="true"/> if <paramref name="obj"/>'s value is in the range as specified; otherwise, <see langword="false"/>.
/// </returns>
///
/// <exception cref="ArgumentOutOfRangeException">
/// Thrown when <paramref name="min"/> is equal or greater than <paramref name="max"/>.
/// </exception>
public static bool InOpenRange<T>(this T obj, in T min, in T max) where T : IComparable
{
if (min.CompareTo(max) >= 0)
throw new ArgumentOutOfRangeException("min should not be equal to or greater than max");
return obj.CompareTo(min) >= 0 && obj.CompareTo(max) < 0;
}
/// <summary>
/// Returns a <see cref="string"/> which describes a list of <c>name/value</c> pairs, of this instance's non-indexed properties.
/// </summary>
///
/// <typeparam name="T">The calling instance's type.</typeparam>
///
/// <param name="t">The calling instance.</param>
/// <param name="separator">Optional: A <see cref="string"/> that will separate between the properties' <see cref="string"/> representations. The default is: <c>new line</c>.</param>
/// <param name="except">Optional: A list of specific properties names, to <b>not</b> include in the returned <see cref="string"/>.</param>
///
/// <returns>
/// A <see cref="string"/> representation of this instance's non-indexed properties.
/// </returns>
public static string ToStringProperties<T>(this T t, in string separator = "\n", params string[] except)
{
string str = "";
if (except.Length == 0)
{
foreach (PropertyInfo item in t.GetType().GetProperties())
if (!item.IsIndexedProperty())
str += item.Name + ": " + item.GetValue(t, null) + separator;
}
else
{
foreach (PropertyInfo item in t.GetType().GetProperties())
if (!item.IsIndexedProperty() && !Array.Exists(except, s => s == item.Name))
str += item.Name + ": " + item.GetValue(t, null) + separator;
}
// Cut off the last separation:
int len = str.Length - separator.Length;
return str.Substring(0, len);
}
/// <summary>
/// Returns a value indicating whether this <see cref="PropertyInfo"/> is an indexed property.
/// </summary>
///
/// <returns>
/// <see langword="true"/> if this property results an empty <see cref="ParameterInfo"/> array; otherwise, <see langword="false"/>.
/// </returns>
public static bool IsIndexedProperty(this PropertyInfo prop)
{
return prop.GetIndexParameters().Length > 0;
}
//public static char[] WhiteSpaces = new char[] { ' ', '\n', '\t', '\r', '\f', '\v' };
#region Random Extensions
/// <summary>
/// Returns a random <see cref="Date"/> between <paramref name="min"/> (including)
/// and <paramref name="max"/> (not including).
/// </summary>
///
/// <param name="min">
/// The lower (inclusive) <see cref="Date"/> bound.
/// </param>
/// <param name="max">
/// The upper (exclusive) <see cref="Date"/> bound. Must be greater than <paramref name="min"/>
/// </param>
///
/// <remarks>
/// If <paramref name="max"/> isn't greater than <paramref name="min"/>, then
/// <paramref name="min"/> is returned.
/// </remarks>
public static Date NextDate(this Random rand, in Date min, in Date max)
{
if (max <= min)
return min;
// Date rang to numeric range:
// min = '0', and max is the number of days to add:
int diff = max - min;
return min + rand.Next(diff);
}
/// <summary>
/// Returns a random <see cref="bool"/> value.
/// </summary>
public static bool NextBoolean(this Random rand) =>
rand.NextDouble() >= 0.5;
/// <summary>
/// Returns a random constant of the specified enumeration of type <typeparamref name="T"/>.
/// </summary>
/// <typeparam name="T">The type of the enumeration (<see cref="Enum"/>).</typeparam>
/// <param name="rand"></param>
/// <returns></returns>
public static T NextConstant<T>(this Random rand) where T : Enum
{
T result = default;
var values = Values<T>();
int x = rand.Next(values.Length + 1);
int i = -1;
foreach (var item in values)
{
if (x == (++i))
{
result = (T)item;
break;
}
}
return result;
}
#endregion
public static Func<T, bool> ToFunc<T>(this Predicate<T> pred) =>
new Func<T, bool>(pred);
/// <summary>
/// Removes the first occurance of an elements that matches the conditions defined by the specified predicate.
/// </summary>
///
/// <typeparam name="T">
/// The list' elements type. Also defines the <see cref="Predicate{T}"/> argument.
/// </typeparam>
///
/// <param name="match">
/// The <see cref="Predicate{T}"/> delegate that defines the conditions of the elements to remove.
/// </param>
///
/// <returns>
/// <see langword="true"/> if found and removed. Otherwise <see langword="false"/>.
/// </returns>
///
/// <exception cref="ArgumentNullException">
/// Occures when <paramref name="list"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentException">
/// Occures when <paramref name="list"/> is an empty <see cref="List{T}"/>.
/// </exception>
public static bool RemoveFirst<T>(this List<T> list, Predicate<T> match = null)
{
if (list == null)
throw new ArgumentNullException("list");
if (list.Count == 0)
throw new ArgumentException("The List<T> argument is an empty list.", "list");
if (match == null)
{
list.RemoveAt(0);
return true;
}
int index = list.FindIndex(match);
if (index == -1)
return false;
list.RemoveAt(index);
return true;
}
#region PropertyInfo Extensions
public static PropertyInfo[] GetProperties(this Type type, params string[] names)
{
if (names == null || names.Length == 0)
return type.GetProperties();
List<PropertyInfo> properties = new List<PropertyInfo>();
foreach (var name in names)
properties.Add(type.GetProperty(name));
return properties.ToArray();
}
public static PropertyInfo GetProperty<T>(this T obj, string name)
=> obj.GetType().GetProperty(name);
public static PropertyInfo[] GetProperties<T>(this T obj, params string[] names)
=> obj.GetType().GetProperties(names);
#endregion
public static Date Min(Date a, Date b)
{
return
b < a ?
b :
a;
}
/// <summary>
/// Indicates whether <paramref name="collection"/> isn't <see langword="null"/>
/// and is empty.
/// </summary>
/// <typeparam name="T">
/// The type of <paramref name="collection"/>'s elements.
/// </typeparam>
/// <param name="collection">
/// The collection to check.
/// </param>
public static bool IsEmptyCollection<T>(IEnumerable<T> collection) =>
collection != null && collection.Count() == 0;
/// <summary>
/// Indicates whether if there is any overlap between the two specified periods.
/// </summary>
/// <remarks>
/// <see cref="ArgumentOutOfRangeException"/> if the dates are out of order (start >= end).
/// </remarks>
public static bool Overlaps(this (Date start, Date end) period, (Date start, Date end) other)
{
if (period.start >= period.end)
throw new ArgumentOutOfRangeException("period");
if (other.start >= other.end)
throw new ArgumentOutOfRangeException("other");
if (period.end <= other.start || other.end <= period.start)
return false;
return true;
}
}
}