-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCollectionExtensions.cs
36 lines (32 loc) · 1.25 KB
/
CollectionExtensions.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
using System;
using System.Collections.Generic;
using System.Linq;
namespace Annoyances.Net
{
/// <summary>
/// More LINQ-like methods. Extension methods for <see cref="ICollection{T}"/>.
/// </summary>
public static class CollectionExtensions
{
/// <summary>
/// Removes the first element for which the specified condition is true
/// </summary>
/// <typeparam name="T">The type of elements in the collection</typeparam>
/// <param name="collection">The collection</param>
/// <param name="predicate">A condition that is true for the elements to be removed</param>
/// <returns>True if an element was removed; false if no element was removed</returns>
public static bool RemoveFirst<T>(this ICollection<T> collection, Func<T, bool> predicate)
{
if (collection == null)
{
throw new ArgumentNullException("collection");
}
if (predicate == null)
{
throw new ArgumentNullException("predicate");
}
T[] oneOrNone = collection.SkipWhile(x => !predicate(x)).Take(1).ToArray();
return oneOrNone.Length != 0 && collection.Remove(oneOrNone[0]);
}
}
}