Created
August 9, 2015 10:19
-
-
Save JamesTryand/075719b9139839aa4afe to your computer and use it in GitHub Desktop.
ArrayList as Enumerable Extension
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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