IgnoreNullItems
以下のサンプル コードで拡張メソッドを呼び出すと、遅延実行は期待どおりに機能しますが、使用するIgnoreNullItemsHavingDifferentBehaviour
とすぐに例外が発生します。なんで?
List<string> testList = null;
testList.IgnoreNullItems(); //nothing happens as expected
testList.IgnoreNullItems().FirstOrDefault();
//raises ArgumentNullException as expected
testList.IgnoreNullItemsHavingDifferentBehaviour();
//raises ArgumentNullException immediately. not expected behaviour ->
// why is deferred execution not working here?
アイデアを共有していただきありがとうございます。
ラファエル・ザゲット
public static class EnumerableOfTExtension
{
public static IEnumerable<T> IgnoreNullItems<T>(this IEnumerable<T> source)
where T: class
{
if (source == null) throw new ArgumentNullException("source");
foreach (var item in source)
{
if (item != null)
{
yield return item;
}
}
yield break;
}
public static IEnumerable<T> IgnoreNullItemsHavingDifferentBehaviour<T>(
this IEnumerable<T> source)
where T : class
{
if (source == null) throw new ArgumentNullException("source");
return IgnoreNulls(source);
}
private static IEnumerable<T> IgnoreNulls<T>(IEnumerable<T> source)
where T : class
{
foreach (var item in source)
{
if (item != null)
{
yield return item;
}
}
yield break;
}
}
同じ動作のバージョンを次に示します。
これは、同じ動作を示すバージョンです。この場合、resharper に foreach ステートメントを「改善」させないでください ;) --> resharper は、return ステートメントを使用して foreach を「IgnoreNullItemsHavingDifferentBehaviour」バージョンに変更します。
public static IEnumerable<T> IgnoreNullItemsHavingSameBehaviour<T>(this IEnumerable<T> source) where T : class
{
if (source == null) throw new ArgumentNullException("source");
foreach (var item in IgnoreNulls(source))
{
yield return item;
}
yield break;
}