List<ImplInterface> ---> IEnumerable<Interface>

  • Thread starter Thread starter Berryl Hesh
  • Start date Start date
B

Berryl Hesh

Converting in the other direction , IEnumerable<Interface> to
List<ImplInterface>, I can just create a new List<ImplInterface> (data)
where data is IEnumerable<Interface>.

How can I convert the List<ImplInterface> to IEnumerable<Interface>?

Thanks, BH
 
Berryl said:
Converting in the other direction , IEnumerable<Interface> to
List<ImplInterface>, I can just create a new List<ImplInterface> (data)
where data is IEnumerable<Interface>.

How can I convert the List<ImplInterface> to IEnumerable<Interface>?
If I understand the question correctly, you have a class ImplInterface that
implements Interface. It's actually unclear to me how you would be able to
convert a generic IEnumerable<Interface> to a List<ImplInterface>: the
Interface elements in the enumerable don't need to be of type ImplInterface.
Is ImplInterface a wrapper type?

The other way around is more obvious, type-wise. If you have C# 3.0 and .NET
3.5, it's as easy as

aListImplInterface.Cast<Interface>()

If you don't, you can write this method yourself:

static class EnumerableConversion {
static IEnumerable<T> Cast<T, U>(IEnumerable<U> source) where U : T {
foreach (U u in source) yield return (T) u;
}
}

And call it like so:

EnumerableConversion.Cast<Interface, ImplInterface>(aListImplInterface)

Not half as snappy, obviously.
 
aListImplInterface.Cast<Interface>()

Snappy indeed, (once I figured out I need the Linq namespace, that is)

In the meantime I'd figured out that making the List type be List<Interface>
instead of List<ImplInterface> was just as good here.

Thanks!
 
Berryl said:
Snappy indeed, (once I figured out I need the Linq namespace, that is)

In the meantime I'd figured out that making the List type be List<Interface>
instead of List<ImplInterface> was just as good here.
Don't forget to consider IList<>, ICollection<> and IEnumerable<> if it's a
type you're offering to clients (in that order), since it's less committing.
 
Back
Top