簡體   English   中英

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

[英]How do I merge non-generic IEnumerable in C#

我試圖讓一個 object 從另一個 object 繼承,其中IEnumerable類型的屬性將合並在一起。

兩個對象都屬於相同的 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
}

LINQ Cast<T>方法允許您將非通用 Enumerable 轉換為通用 Enumerable。 假設您知道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>());
}

如果不知道具體類型,也可以轉為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