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

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
 
J

Jeroen Mostert

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.
 
B

Berryl Hesh

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!
 
J

Jeroen Mostert

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top