简体   繁体   中英

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 parentIEnumberable = parentProperty as IEnumerable;

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

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>());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM