4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

foreach で列挙されない場合に処理を実行する

Last updated at Posted at 2013-04-06

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();
    }
}
4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?