public
Created

Enumerable "converter" (w/ lambda)

  • Download Gist
EnumHelper.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
using System;
using System.Collections;
using System.Collections.Generic;
 
namespace EnumHelper
{
public class EnumeratorAdapter<T, K> : IEnumerator<K>
{
private IEnumerator<T> Enumerator = null;
 
private Func<T, K> Map = null;
 
public EnumeratorAdapter(IEnumerator<T> enumerator, Func<T, K> map)
{
Enumerator = enumerator;
Map = map;
}
 
void IDisposable.Dispose() { Enumerator.Dispose(); }
 
object IEnumerator.Current { get { return Current; } }
 
public bool MoveNext() { return Enumerator.MoveNext(); }
public void Reset() { Enumerator.Reset(); }
public K Current { get { return Map(Enumerator.Current); } }
}
 
public class EnumerableAdapter<T> : IEnumerable<T>
{
private IEnumerator<T> enumeratorAdaper = null;
public EnumerableAdapter(IEnumerator<T> enumAdaper) { enumeratorAdaper = enumAdaper; }
public IEnumerator<T> GetEnumerator() { return enumeratorAdaper; }
IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }
}
 
public static class EnumerableAdapterHelper
{
public static IEnumerable<K> MapEnum<T, K>(this IEnumerable<T> ienum, Func<T, K> map)
{
return new EnumerableAdapter<K>(new EnumeratorAdapter<T, K>(ienum.GetEnumerator(), map));
}
}
}
List<string> l = new List<string>();
l.Add("1");
l.Add("2");
l.Add("3");
var intenum = l.MapEnum<string, int>(s => int.Parse(s));
foreach (int p in intenum)
  System.Console.WriteLine(p * 10);

I know you can just use Linq...

List<string> mylist = new List<string>();
mylist.Add("1");
mylist.Add("2");
mylist.Add("3");
var newlist = from li in mylist select int.Parse(li);

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.