In reference to @walpen's answer pointing out All
is a Linq
extension (defined in System.Linq.Enumerable
).
I wanted to provide a .NET 2.0 implementation of All
, as an extension.
First, we'll define an Attribute
called ExtensionAttribute
. (SO reference: Using extension methods in .NET 2.0?)
namespace System.Runtime.CompilerServices
{
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class
| AttributeTargets.Method)]
public sealed class ExtensionAttribute : Attribute { }
}
Then, ( by way of magic) we can use the this
reference for extensions. So, we'll create a static class
for the usage of the ExtensionAttribute
: I choose to do so by defining a static class
named Enumerable in System.Collections.Generic
namespace.
namespace System.Collections.Generic
{
public static class Enumerable
{
//[System.Runtime.CompilerServices.Extension()]
public static bool All<T>(this IEnumerable<T> list, T expectedAnswer)
where T : IEquatable<T>, IComparable<T>
{
bool result = true;
IEnumerator<T> enumerator = list.GetEnumerator();
while (enumerator.MoveNext())
{
result = result && (Object.Equals(enumerator.Current, expectedAnswer));
if (!result)
return result;
}
return result;
}
public delegate bool MyFunc<T>(T next);
public static bool All<T>(this IEnumerable<T> list, MyFunc<T> fn)
where T : IEquatable<T>, IComparable<T>
{
bool result = true;
IEnumerator<T> enumerator = list.GetEnumerator();
while (enumerator.MoveNext())
{
result = result && fn.Invoke(enumerator.Current);
if (!result)
return result;
}
return result;
}
}
}
Then, it's a simple matter of using it.
IEnumerable<int> ints = new int[] { 2 + 2, 2 * 2, 1 * 3 + 1 };
Console.Write("Result := {0}", ints.All(4)); // outputs "Result := true"
Console.Write("Result := {0}", ints.All(t => t.Equals(4))); // outputs "Result := true"