Skip to content

Commit 6071164

Browse files
committed
Add some extension methods for collections
Some methods missing from earlier versions of .NET
1 parent d5bd8d6 commit 6071164

1 file changed

Lines changed: 77 additions & 0 deletions

File tree

src/ExtensionMethods.cs

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
using System;
2+
using System.Collections.Generic;
23
using System.Linq;
34
using System.Reflection;
45

@@ -30,5 +31,81 @@ public static string[] Metadata(this Assembly assembly, string key)
3031
}
3132

3233
#endregion
34+
35+
#region Enumberables
36+
37+
public static HashSet<T> ToHashSet<T>(this IEnumerable<T> collection)
38+
{
39+
HashSet<T> set = new HashSet<T>();
40+
41+
foreach (T item in collection)
42+
{
43+
set.Add(item);
44+
}
45+
46+
return set;
47+
}
48+
49+
#endregion
50+
51+
#region Collections
52+
53+
#if NETFRAMEWORK || NETSTANDARD2_0
54+
55+
// Stack<T>
56+
public static bool TryPop<T>(this Stack<T> stack, out T value)
57+
{
58+
if (stack.Count > 0)
59+
{
60+
value = stack.Pop();
61+
return true;
62+
}
63+
64+
value = default;
65+
return false;
66+
}
67+
68+
// Stack<T>
69+
public static bool TryPeek<T>(this Stack<T> stack, out T value)
70+
{
71+
if (stack.Count > 0)
72+
{
73+
value = stack.Peek();
74+
return true;
75+
}
76+
77+
value = default;
78+
return false;
79+
}
80+
81+
// Queue<T>
82+
public static bool TryDequeue<T>(this Queue<T> queue, out T value)
83+
{
84+
if (queue.Count > 0)
85+
{
86+
value = queue.Dequeue();
87+
return true;
88+
}
89+
90+
value = default;
91+
return false;
92+
}
93+
94+
// Queue<T>
95+
public static bool TryPeek<T>(this Queue<T> queue, out T value)
96+
{
97+
if (queue.Count > 0)
98+
{
99+
value = queue.Peek();
100+
return true;
101+
}
102+
103+
value = default;
104+
return false;
105+
}
106+
107+
#endif
108+
109+
#endregion
33110
}
34111
}

0 commit comments

Comments
 (0)