Concat/Union Tables in LINQ

后端 未结 2 570
盖世英雄少女心
盖世英雄少女心 2021-01-13 07:17

This current project is more of a proof of concept for a larger project. I have two \"tables\" (represented as lists below), CatList and DogList, t

相关标签:
2条回答
  • 2021-01-13 07:36

    The issue is that the compiler can't figure out that by concatenating a List<Dog> and a List<Cat> it should produce a collection of iAnimals. By default it sees a List<Dog> and expects the following collection to be a collection of Dog too.

    You can explicitly tell to treat everything as an iAnimal this by providing the generic parameter to Concat, i.e.

    var result = DogList.Concat<iAnimal>(CatList);
    

    You then get a result of type IEnumerable<iAnimal>.

    Edit: If you're stuck on .NET 3.5, you'll need something like

    var result = DogList.Cast<IAnimal>().Concat(CatList.Cast<IAnimal>());
    

    as 3.5 can't automatically convert collection of something that inherits iAnimal to collection of iAnimal.

    0 讨论(0)
  • 2021-01-13 07:41

    The generic lists are from different types (Dog and Cat), you have to "cast" them to the target interface before concatenation:

    var list1 = DogList.Cast<IAnimal>();
    var list2 = CatList.Cast<IAnimal>();
    
    var bothLists = list1.Concat(list2); //optional .ToList()
    
    0 讨论(0)
提交回复
热议问题