Jason Liu
Jason Liu

Reputation: 1

How do I merge non-generic IEnumerable in C#

I'm trying to have one object inherit from another object where properties of type IEnumerable will be merged together.

Both objects are of same class.

foreach (var property in typeof(Placeholder).GetProperties())
{
    var childProperty = property.GetValue(childPlaceholder);
    var parentProperty = property.GetValue(parentPlaceholder);

    IEnumerable childIEnumerable = childProperty as IEnumerable;
    IEnumerable parentIEnumerable = parentProperty as IEnumerable;

    // How do I merge childIEnumerable with parentIEnumerable into one IEnumerable
}

Upvotes: 0

Views: 284

Answers (1)

V0ldek
V0ldek

Reputation: 10613

There's the LINQ Cast<T> method that allows you to turn a non-generic Enumerable to a generic one. Assuming that you know the Parent and Child types (where Child : Parent):

foreach (var property in typeof(Placeholder).GetProperties())
{
    var childProperty = property.GetValue(childPlaceholder);
    var parentProperty = property.GetValue(parentPlaceholder);
    IEnumerable childIEnumerable = childProperty as IEnumerable;
    IEnumerable parentIEnumerable = parentProperty as IEnumerable;
    IEnumerable<Parent> mergedEnumerable = childIEnumerable
        .Cast<Child>()
        .Concat(parentIEnumerable.Cast<Parent>());
}

If you don't know the specific types, you can also cast them to object:

IEnumerable<object> merged = childIEnumerable
    .Cast<object>()
    .Concat(parentIEnumerable.Cast<object>());

Upvotes: 0

Related Questions