foreach で break された場合に処理を実行するの応用?
この間作ってみて便利だったので。
Any() とか使うと 2 回列挙するから ReSharper 先生に怒られちゃう>< ってときに。
EnumerableExTest.cs
[TestClass]
public class EnumerableExTest
{
[TestMethod]
public void EmptyTest()
{
var called = false;
var array = new object[0];
foreach (var item in array.IfEmpty(() => called = true))
{
Console.WriteLine(item);
}
called.IsTrue();
}
[TestMethod]
public void NotEmptyTest()
{
var called = false;
var array = new[] { 1 };
foreach (var item in array.IfEmpty(() => called = true))
{
Console.WriteLine(item);
}
called.IsFalse();
}
}
EnumerableEx.cs
public static class EnumerableEx
{
public static IEnumerable<T> IfEmpty<T>(this IEnumerable<T> source, Action action)
{
var isEmpty = true;
foreach (var item in source)
{
isEmpty = false;
yield return item;
}
if (isEmpty) action();
}
}