What is the best way to convert an IEnumerator to a generic IEnumerator?
Asked Answered
O

5

31

I am writing a custom ConfigurationElementCollection for a custom ConfigurationHandler in C#.NET 3.5 and I am wanting to expose the IEnumerator as a generic IEnumerator.

What would be the best way to achieve this?

I am currently using the code:

public new IEnumerator<GenericObject> GetEnumerator()
{
  var list = new List();
  var baseEnum = base.GetEnumerator();
  while(baseEnum.MoveNext())
  {
    var obj = baseEnum.Current as GenericObject;
    if (obj != null)
      list.Add(obj);
  }
  return list.GetEnumerator();
}

Cheers

Odel answered 6/5, 2009 at 6:54 Comment(0)
N
58

I don't believe there's anything in the framework, but you could easily write one:

IEnumerator<T> Cast<T>(IEnumerator iterator)
{
    while (iterator.MoveNext())
    {
        yield return (T) iterator.Current;
    }
}

It's tempting to just call Enumerable.Cast<T> from LINQ and then call GetEnumerator() on the result - but if your class already implements IEnumerable<T> and T is a value type, that acts as a no-op, so the GetEnumerator() call recurses and throws a StackOverflowException. It's safe to use return foo.Cast<T>.GetEnumerator(); when foo is definitely a different object (which doesn't delegate back to this one) but otherwise, you're probably best off using the code above.

Nerynesbit answered 6/5, 2009 at 7:18 Comment(15)
Can't you just return the Enumerator from cast? return this.Cast<T>().GetEnumerator();Lombroso
@flq, Jon: I am doing the this.Cast<T>().GetEnumerator() solution, in the same scenario (though I am deriving from IEnumerable<T>), and I am getting a stack overflow.Bratcher
@Merlyn: I suggest you post a short but complete example as another Stack Overflow question.Nerynesbit
@Jon: Your original yield return suggestion solves my problem, as does using OfType instead. But I can post a question anyway.Bratcher
@Merlyn: If you're interested in what's going wrong, then go ahead - I can't quite imagine what you're doing at the moment, so it's hard to say really.Nerynesbit
Use OfType<T>() to avoid the stack overflow exception, see bug report connect.microsoft.com/VisualStudio/feedback/details/713688/…Modulator
@MerlynMorgan-Graham: we had exactly the same problem with a Stack Overflow when trying to implement IEnumerator<T> in a class derived from ConfigurationElementCollection and implementing ICollection<T>Antigone
I was running into the same Stack Overflow problem. In my case it was due to the fact that the GetEnumerator needed to be to the base.GetEnumerator otherwise you loop within your own GetEnumerator redefinition.Bialystok
@VeV: Without seeing the exact code, it's hard to know exactly what's going on there - as per my response to Merlyn, it would be good to ask a new question.Nerynesbit
@HaraldDutch: Please don't perform such significant edits to answers; I'd be happy to edit the answer when it's actually clear what's wrong, but Merlyn Morgan-Graham's comment about a stack overflow didn't actually provide an example. Using OfType will not do the same as Cast. I'll edit to clarify the difference between them.Nerynesbit
It throws a StackOverflowException if the class implements IEnumerable<T> because Cast<T> returns source as IEnumerable<T> if it's not null. referencesource.microsoft.com/#System.Core/System/Linq/…Monoxide
@borigas: How would that mean it throws a StackOverflowException? That doesn't recurse... (I still haven't reproduced this StackOverflowException...)Nerynesbit
Cast<T> isn't where the StackOverflowException occurs, but when it returns source as IEnumerable<T> without doing anything, it's effectively a noop, turning it into public IEnumerator<T> GetEnumerator() { return this.GetEnumerator(); } See dotnetfiddle.net/Vh1USx for an exampleMonoxide
@borigas: Ah, I see. But your fiddle leaves out the new part, which would prevent recursion, I believe - by delegating to the IEnumerable<T>.GetEnumerator() call. But there's definitely room for doubt - I'll see if I can provoke it using exactly my code.Nerynesbit
@borigas: And now I've found out how to... will edit.Nerynesbit
L
3

IEnumerable<T> already derives from IEnumerable so there's no need to do any conversion. You can simply cast to it...well actually it's implicit no cast necessary.

IEnumerable<T> enumerable = GetGenericFromSomewhere();
IEnumerable sadOldEnumerable = enumerable;
return sadOldEnumerable.GetEnumerator();

Going the other way round isn't much more difficult with LINQ:

var fancyEnumerable = list.OfType<GenericObject>();
return fancyEnumerable.GetEnumerator();
Leatherneck answered 6/5, 2009 at 6:57 Comment(6)
My bad missed the generic part to my method definitionOdel
You are confusing IEnumerable and IEnumerator. IEnumerable<T> derives from IEnumerable and IEnumerator<T> derives from IEnumerator. It doesn't make much sense to say "IEnumerable<T> theEnumerator" because an enumerable is not an enumerator.Tattered
casting does not work as the in the parent object the collection is stored in an ArrayList.Odel
Yep - read it too quickly. But the answer still applies. I'll fix it to reflect the correct classes.Leatherneck
It does not work for the case: var genericEnumerator = (IEnumerator<int>)new ArrayList { 1 }.GetEnumerator(); throws exception: System.InvalidCastException: Unable to cast object of type 'ArrayListEnumeratorSimple' to type 'System.Collections.Generic.IEnumerator`1[System.Int32]'.Odel
You can't cast from non-generic to generic. You have to use the OfType method mentioned in the second portion. You can only cast from generic to non-generic.Leatherneck
S
1

You can use OfType<T> and Cast<T>.

public static IEnumerable Digits()
{
    return new[]{1, 15, 68, 1235, 12390, 1239};
}

var enumerable = Digits().OfType<int>();
foreach (var item in enumerable)
    // var is here an int. Without the OfType<int(), it would be an object
    Console.WriteLine(i);

To get an IEnumerator<T> instead of an IEnumerable<T> you can just make a call to GetEnumerator()

var enumerator = Digits().OfType<int>().GetEnumerator();
Shamanism answered 6/5, 2009 at 13:18 Comment(0)
B
1

I was running into the same Stack Overflow problem mentioned is some of the comments. In my case it was due to the fact that the GetEnumerator call needed to be to the base.GetEnumerator otherwise you loop within your own GetEnumerator redefinition.

This is the code that was Throwing the Stack Overflow. The use of the foreach statement call the same GetEnumerator function I'm trying to overload:

public new IEnumerator<T> GetEnumerator()
{
    foreach (T type in this)
    {
        yield return type;
    }
}

I've ended up with a simplified version of the original post as you don't need to use a List holder.

public class ElementCollection<T> : ConfigurationElementCollection, IList<T>
    ...
    public new IEnumerator<T> GetEnumerator()
    {
        var baseEnum = base.GetEnumerator();
        while (baseEnum.MoveNext())
        {
            yield return baseEnum.Current as T;
        }
    }
    ...
}
Bialystok answered 10/6, 2015 at 23:17 Comment(0)
T
0

This works for me.

IEnumerator<DataColumn> columnEnumerator = dt.Columns.Cast<DataColumn>().GetEnumerator();
Thoth answered 16/12, 2014 at 17:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.