/
UniqueIntegerCollection.cs
343 lines (298 loc) · 13.2 KB
/
UniqueIntegerCollection.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
//===============================================================================================================
// System : Personal Data Interchange Classes
// File : UniqueIntegerCollection.cs
// Author : Eric Woodruff (Eric@EWoodruff.us)
// Updated : 11/23/2018
// Note : Copyright 2003-2018, Eric Woodruff, All rights reserved
// Compiler: Microsoft Visual C#
//
// This file contains a type-safe collection class that is used to contain a set of unique integer values with
// an optional range restriction and zero exclusion.
//
// This code is published under the Microsoft Public License (Ms-PL). A copy of the license should be
// distributed with the code and can be found at the project website: https://github.com/EWSoftware/PDI.
// This notice, the author's name, and all copyright notices must remain intact in all applications,
// documentation, and source files.
//
// Date Who Comments
// ==============================================================================================================
// 08/12/2004 EFW Created the code
// 03/05/2007 EFW Converted to use a generic base class
//===============================================================================================================
// Ignore Spelling: ic
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
namespace EWSoftware.PDI
{
/// <summary>
/// A type-safe collection of unique integer values with an optional range restriction and zero exclusion
/// </summary>
[Serializable]
public class UniqueIntegerCollection : Collection<int>
{
#region Private data members
//=====================================================================
// These are used to parse a string of values for adding into the collection
private static Regex reStripNonDigits = new Regex(@"[^0-9\-,]");
private static Regex reIsRange = new Regex("(?<=[^-])-");
#endregion
#region Properties
//=====================================================================
/// <summary>
/// This read-only property is used to get the minimum value allowed to be added to the collection
/// </summary>
public int MinimumValue { get; }
/// <summary>
/// This read-only property is used to get the highest value allowed to be added to the collection
/// </summary>
public int MaximumValue { get; }
/// <summary>
/// This read-only property is used to get whether or not zero is allowed as a valid value
/// </summary>
/// <value>This is useful if you need to set a valid range that includes negative and positive values but
/// excludes zero (i.e. -53 to -1 and +1 to +53 but not zero).</value>
public bool AllowZero { get; }
#endregion
#region Constructors
//=====================================================================
/// <summary>
/// Default constructor
/// </summary>
/// <remarks>No validation range is defined and zero is allowed</remarks>
/// <overloads>There are five overloads for the constructor</overloads>
public UniqueIntegerCollection()
{
this.MinimumValue = Int32.MinValue;
this.MaximumValue = Int32.MaxValue;
this.AllowZero = true;
}
/// <summary>
/// Construct a collection with a range and zero exclusion option
/// </summary>
/// <param name="min">The minimum value allowed</param>
/// <param name="max">The maximum value allowed</param>
/// <param name="zeroAllowed">Allow zero or not</param>
public UniqueIntegerCollection(int min, int max, bool zeroAllowed)
{
this.MinimumValue = min;
this.MaximumValue = max;
this.AllowZero = zeroAllowed;
}
/// <summary>
/// Construct a collection from an enumerable list of unique integers without range checking and with
/// zero allowed.
/// </summary>
/// <param name="values">The enumerable list of integers</param>
public UniqueIntegerCollection(IEnumerable<int> values) : this()
{
if(values != null)
this.AddRange(values);
}
/// <summary>
/// Construct a collection from an enumerable list of unique integers with a range and zeros exclusion
/// setting.
/// </summary>
/// <param name="values">The enumerable list of integers</param>
/// <param name="min">The minimum value allowed</param>
/// <param name="max">The maximum value allowed</param>
/// <param name="zeroAllowed">Allow zero or not</param>
public UniqueIntegerCollection(IEnumerable<int> values, int min, int max, bool zeroAllowed) :
this(min, max, zeroAllowed)
{
if(values != null)
this.AddRange(values);
}
/// <summary>
/// Copy constructor
/// </summary>
/// <param name="values">The <c>UniqueIntegerCollection</c> to copy. The range and zero exclusion
/// setting are inherited from the copied collection.</param>
public UniqueIntegerCollection(UniqueIntegerCollection values)
{
if(values != null)
{
this.MinimumValue = values.MinimumValue;
this.MaximumValue = values.MaximumValue;
this.AllowZero = values.AllowZero;
this.AddRange(values);
}
}
#endregion
#region Methods
//=====================================================================
/// <summary>
/// Add a range of integers from an enumerable list
/// </summary>
/// <param name="values">The enumerable list of integers</param>
public void AddRange(IEnumerable<int> values)
{
if(values != null)
foreach(int v in values)
base.Add(v);
}
/// <summary>
/// Insert an integer into the collection
/// </summary>
/// <param name="index">The index at which to insert the integer</param>
/// <param name="item">The integer to insert</param>
/// <remarks>If the integer already exists in the collection, it will be moved to the new position</remarks>
/// <exception cref="ArgumentOutOfRangeException">This is thrown if the value is less than
/// <see cref="MinimumValue"/> or greater than <see cref="MaximumValue"/>.</exception>
/// <exception cref="ArgumentException">This is thrown if the value is zero and zeros are not allowed in
/// the collection.</exception>
protected override void InsertItem(int index, int item)
{
if(item < this.MinimumValue || item > this.MaximumValue)
throw new ArgumentOutOfRangeException(nameof(item), item, LR.GetString("ExUICValueOutOfRange"));
if(item == 0 && !this.AllowZero)
throw new ArgumentException(LR.GetString("ExUICZerosNotAllowed"), nameof(item));
int curIdx = base.IndexOf(item);
if(curIdx == -1)
base.InsertItem(index, item);
else
if(index != curIdx)
{
base.RemoveAt(curIdx);
if(index > base.Count)
base.InsertItem(base.Count, item);
else
base.InsertItem(index, item);
}
}
/// <summary>
/// Set an item in the collection
/// </summary>
/// <param name="index">The index of the item to set</param>
/// <param name="item">The integer value to store</param>
/// <remarks>If the integer already exists in the collection, it will be moved to the new position</remarks>
protected override void SetItem(int index, int item)
{
int curIdx = base.IndexOf(item);
if(curIdx == -1)
base.SetItem(index, item);
else
if(index != curIdx)
this.InsertItem(index, item);
}
/// <summary>
/// Remove a range of items from the collection
/// </summary>
/// <param name="index">The zero-based index at which to start removing items</param>
/// <param name="count">The number of items to remove</param>
public void RemoveRange(int index, int count)
{
((List<int>)base.Items).RemoveRange(index, count);
}
/// <summary>
/// This is used to sort the collection in ascending or descending order
/// </summary>
/// <param name="ascending">Pass true for ascending order, false for descending order</param>
public void Sort(bool ascending)
{
((List<int>)base.Items).Sort((x, y) =>
{
if(ascending)
return x.CompareTo(y);
return y.CompareTo(x);
});
}
/// <summary>
/// This is used to get a string containing the values in the collection
/// </summary>
/// <returns>A string containing the values. Ranges of consecutive values are compressed into an "X-Y"
/// format. For example: 1,10,15-20,30-35,100</returns>
public override string ToString()
{
StringBuilder sb = new StringBuilder(256);
int idx, value, startValue, count = base.Count;
// Copy the items to an array and sort them in ascending order. We do this so as not to disturb the
// order of the collection.
int[] array = new int[base.Count];
base.CopyTo(array, 0);
Array.Sort(array);
for(idx = 0; idx < count; idx++)
{
if(idx != 0)
sb.Append(',');
value = array[idx];
sb.Append(value);
if(idx < count - 1 && array[idx + 1] == value + 1)
{
startValue = value;
while(idx < count - 1 && array[idx + 1] == value + 1)
{
idx++;
value = array[idx];
}
// If it's only one greater, use a comma
if(value == startValue + 1)
sb.AppendFormat(",{0}", value);
else
sb.AppendFormat("-{0}", value);
}
}
return sb.ToString();
}
/// <summary>
/// This is used to parse a set of individual numbers or ranges of numbers from a string and store them
/// in the collection.
/// </summary>
/// <param name="values">The string containing the values to parse and store</param>
/// <remarks>Any values that are not valid are discarded</remarks>
/// <example>
/// <code language="cs">
/// UniqueIntegerCollection ic = new UniqueIntegerCollection();
/// ic.ParseValues("1, 10, 15-20, 30-35, 100");
/// </code>
/// <code language="vbnet">
/// Dim ic As New UniqueIntegerCollection()
/// ic.ParseValues("1, 10, 15-20, 30-35, 100")
/// </code>
/// </example>
public void ParseValues(string values)
{
string[] parts, range;
int value;
// Remove all characters that are not a digit, dash, or comma
string parse = reStripNonDigits.Replace(values, String.Empty);
parts = parse.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
foreach(string s in parts)
if(!reIsRange.IsMatch(s))
{
// Single value. Discard invalid and out of range entries.
if(Int32.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out value) &&
value >= this.MinimumValue && value <= this.MaximumValue && (value != 0 || this.AllowZero))
base.Add(value);
}
else
{
// Range of values
range = reIsRange.Split(s);
// Discard invalid entries
if(Int32.TryParse(range[0], NumberStyles.Integer, CultureInfo.InvariantCulture, out int low) &&
Int32.TryParse(range[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out int high))
{
// Flip the range if necessary
if(low > high)
{
value = low;
low = high;
high = value;
}
// Out of range values are discarded
while(low <= high)
{
if(low >= this.MinimumValue && low <= this.MaximumValue && (low != 0 || this.AllowZero))
base.Add(low);
low++;
}
}
}
}
#endregion
}
}