-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathListUtilities.cs
More file actions
98 lines (58 loc) · 2.54 KB
/
ListUtilities.cs
File metadata and controls
98 lines (58 loc) · 2.54 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
using Gsemac.Collections.Extensions;
using Gsemac.Collections.Properties;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Gsemac.Collections {
public static class ListUtilities {
// Public members
public static void Move<T>(IList<T> items, int oldIndex, int newIndex) {
if (items is null)
throw new ArgumentNullException(nameof(items));
if (oldIndex < 0 || oldIndex > items.Count - 1)
throw new ArgumentOutOfRangeException(nameof(oldIndex), ExceptionMessages.IndexOutOfRange);
if (newIndex < 0)
throw new ArgumentOutOfRangeException(nameof(newIndex), ExceptionMessages.IndexOutOfRange);
// Remove the old item.
T item = items[oldIndex];
items.RemoveAt(oldIndex);
// Insert the new item.
items.Insert(newIndex, item);
}
public static void RemoveAll<T>(IList<T> items, int[] indicesToRemove) {
if (items is null)
throw new ArgumentNullException(nameof(items));
if (indicesToRemove is object) {
// Items are removed by index in descending order so that their positions remain constant.
// https://stackoverflow.com/a/9908607
foreach (int index in indicesToRemove.OrderByDescending(i => i)) {
if (index < 0 || index > items.Count)
throw new IndexOutOfRangeException(ExceptionMessages.IndexOutOfRange);
items.RemoveAt(index);
}
}
}
public static void RemoveAll<T>(IList<T> items, IEnumerable<T> itemsToRemove) {
if (items is null)
throw new ArgumentNullException(nameof(items));
if (itemsToRemove is object && itemsToRemove.Any()) {
foreach (T item in itemsToRemove)
items.Remove(item);
}
}
public static void RemoveDuplicates<T>(IList<T> items) {
if (items is null)
throw new ArgumentNullException(nameof(items));
HashSet<T> itemsLookup = new HashSet<T>();
List<T> distinctItems = new List<T>(items.Count);
foreach (T item in items) {
if (!itemsLookup.Contains(item)) {
itemsLookup.Add(item);
distinctItems.Add(item);
}
}
items.Clear();
items.AddRange(distinctItems);
}
}
}