首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >连接两个类型不同但超类相同的列表

连接两个类型不同但超类相同的列表
EN

Stack Overflow用户
提问于 2019-08-01 20:39:03
回答 4查看 140关注 0票数 0

我想知道是否可以将两个不同类型但都具有相同super类的列表合并在一起

代码语言:javascript
运行
复制
public class A : super {}
public class B : super {}


ListA<super> ListA = new List<super>();

ListA<B> ListA = new List<B>();

我想将这两个列表组合成如下内容:

代码语言:javascript
运行
复制
List <super> ListCombined = new List <super>();

还要注意,AB具有相同的super

EN

回答 4

Stack Overflow用户

发布于 2019-08-01 20:44:36

您可以尝试Linq

代码语言:javascript
运行
复制
   ListCombined = ListA
     .OfType<super>()
     .Concat(ListB)
     .ToList(); 

AddRange (无Linq解决方案):

代码语言:javascript
运行
复制
   List<super> ListCombined = new List<super>();

   ListCombined.AddRange(ListA);
   ListCombined.AddRange(ListB);
票数 3
EN

Stack Overflow用户

发布于 2019-08-01 20:58:36

可能:

代码语言:javascript
运行
复制
using System;
using System.Collections.Generic;

public static class Program {
    public static void Main() {
        List<ExtendedCar1> cars1 = new List<ExtendedCar1>{
            new ExtendedCar1{Brand = "Audi", Model = "R8"},
            new ExtendedCar1{Brand = "Bentley", Model = "Azure"}
        };

        List<ExtendedCar2> cars2 = new List<ExtendedCar2>{
            new ExtendedCar2{Brand = "Ferrari", Color ="Red"},
            new ExtendedCar2{Brand = "Maruti", Color ="Saffire Blue"}
        };

        List<Car> cars = new List<Car>(cars1);
        cars.AddRange(cars2);

        foreach(var car in cars){
            Console.WriteLine($"Car Brand: {car.Brand}");
        }

    }

}


public class Car{
   public String Brand {get;set;}    
}

public class ExtendedCar1 : Car {
   public String Model{get;set;}    
}

public class ExtendedCar2: Car {
   public String Color {get;set;}    
}

输出:

票数 1
EN

Stack Overflow用户

发布于 2019-08-01 20:51:57

我猜你说的超级是指基类?

代码语言:javascript
运行
复制
public class Parent 
{

   public List<ChildA> ChildListA { get; set;}
   public List<ChildB> ChildListB { get; set;}

}

public class ChildA:Parent
{

}
public class ChildB:Parent
{

}

var parentList= new List<Parent>();

parentList.Add( new Parent() { ChildListA=new List<ChildA>(),  ChildListB=new List<ChildB>()}); 
// assuming parent is not abstract
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57309257

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档