简体   繁体   English

如何在 C# 中合并非通用 IEnumerable

[英]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.我试图让一个 object 从另一个 object 继承,其中IEnumerable类型的属性将合并在一起。

Both objects are of same class.两个对象都属于相同的 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. LINQ Cast<T>方法允许您将非通用 Enumerable 转换为通用 Enumerable。 Assuming that you know the Parent and Child types (where Child: Parent ):假设您知道ParentChild类型(其中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 :如果不知道具体类型,也可以转为object

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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