-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathHasDuplicate.cs
39 lines (31 loc) · 1.1 KB
/
HasDuplicate.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
public static class ExtentionCollection
{
public static bool HasDuplicate<T>(this ICollection<T> collection, out int indexOfDuplicateValue)
where T : struct
{
var localCollection = collection;
if(localCollection is null)
throw new NullReferenceException();
if(localCollection.Count == 0)
throw new Exception("Collection is empty");
HashSet<T> list = new();
var result = !localCollection.All(c => list.Add(c) );
indexOfDuplicateValue = result ? list.Count : -1;
return result;
}
public static bool HasDuplicate(this ICollection<string> collection,
out int indexOfDuplicateValue, bool isCaseSensitive = false)
{
var localCollection = collection;
if (localCollection is null)
throw new NullReferenceException();
if (localCollection.Count == 0)
throw new Exception("Collection is empty");
localCollection = !isCaseSensitive ?
collection.Select(c => c?.ToLower() ).ToArray() : localCollection ;
HashSet<string> list = new();
var result = !localCollection.All(c => list.Add(c));
indexOfDuplicateValue = result ? list.Count : -1;
return result;
}
}