c# assemble 多个列表 <derived class> 的元素到唯一列表 <base class> 的最佳方法

c# best way to assemble multiple list<derived class>s' elements to sole list<base class>

我正在尝试制作具有多个列表的数据容器 class, 我想让 属性 提供将这些列表的元素收集到一个列表

我应该像下面那样编写 GatherAllCards() 代码,还是有任何压缩代码的好方法。

classes named card* 派生自 class of Card

public class CardContainer : MonoSingleon<CardContainer>
{
    [SerializeField]
    private List<CardUnit> cardUnits;
    [SerializeField]
    private List<CardPlayerUnit> cardPlayerUnits;
    [SerializeField]
    private List<CardConsumable> cardConsumables;
    [SerializeField]
    private List<CardWeapon> cardWeapons;
    [SerializeField]
    private List<Card> cardBases;

    public IReadOnlyList<Card> AllCard
    {
        private set;
        get;
    }

    private void GatherAllCards()
    {
        List<Card> cardList = new List<Card>(500);

        foreach (var card in cardUnits)
            cardList.Add(card);
        foreach (var card in cardPlayerUnits)
            cardList.Add(card);
        foreach (var card in cardConsumables)
            cardList.Add(card);
        foreach (var card in cardWeapons)
            cardList.Add(card);
        foreach (var card in cardBases)
            cardList.Add(card);

        AllCard = cardList.AsReadOnly();
    }
}

使用 AddRange, which takes an IEnumerable<Card>. IEnumerable<T> is covariant,所以传递一个 List<SpecificTypeOfCard> 就可以了。

cardList.AddRange(cardUnits);
cardList.AddRange(cardPlayerUnits);
cardList.AddRange(cardConsumables);
cardList.AddRange(cardWeapons);
cardList.AddRange(cardBases);

或者另一种方法是 Concat,您只需要先转换为 Card

Concatenates two sequences.

AllCard = cardUnits
  .Cast<Card>()
  .Concat(cardPlayerUnits)
  .Concat(cardConsumables)
  .Concat(cardWeapons)
  .Concat(cardBases)
  .ToList();

AllCard = new List<Card>()
  .Concat(cardUnits)
  .Concat(cardPlayerUnits)
  .Concat(cardConsumables)
  .Concat(cardWeapons)
  .Concat(cardBases)
  .ToList();

您也可以使用 Union,但它确实有细微差别