Skip to content

Instantly share code, notes, and snippets.

@JamesTryand
Created August 9, 2015 10:19
Show Gist options
  • Save JamesTryand/075719b9139839aa4afe to your computer and use it in GitHub Desktop.
Save JamesTryand/075719b9139839aa4afe to your computer and use it in GitHub Desktop.
ArrayList as Enumerable Extension
using System.Collections;
using System.Collections.Generic;
namespace System.CollectionsEx
{
public static class ArrayListExtensions
{
public static IEnumerable<T> AsEnumerable<T>(this ArrayList collection)
{
return new ArrayListEnumerable(collection).AsEnumerable<T>();
}
private class ArrayListEnumerable
{
private ArrayList collection;
private bool AnyOfType;
public ArrayListEnumerable(ArrayList collection)
{
this.collection = collection;
AnyOfType = false;
}
public IEnumerable<T> AsEnumerable<T>()
{
foreach (var item in collection)
{
if (item is T)
{
if (AnyOfType != true)
{
AnyOfType = true;
}
yield return (T)item;
}
}
if (!AnyOfType)
{
T thing = default(T);
yield return thing;
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment