首页 > 解决方案 > 有没有办法在 c# 中将 2 种不同类型添加到新列表中?

问题描述

我正在尝试将 2 个列表添加在一起,但它们都是不同的类型,有没有办法做到这一点?

我的 2 个清单

var customer = _context.GetInsuredData.FromSqlRaw("Execute dbo.GetDataID {0}", id).ToList();
var vehicle = _context.GetVehicleData.FromSqlRaw("Execute dbo.GetDataVehicle {0}", id).ToList();

我的背景:

 public virtual DbQuery<Insured> GetInsuredData { get; set; }
 public virtual DbQuery<Vehicle> GetVehicleData { get; set; }

标签: c#entity-framework-core

解决方案


对的,这是可能的。

选项 1 - 让类实现一个公共接口(或继承一个公共基类):

public interface ICommonInterface
{ }

public class Insured : ICommonInterface
{ }

public class Vehicle : ICommonInterface
{ }

...然后使用具有接口泛型类型的列表:

var list = new List<ICommonInterface>();
objectList.AddRange(insureds);
objectList.AddRange(vehicles);

选项 2 - 使用泛型类型声明一个列表object

var list = new List<object>();
list.AddRange(insureds);
list.AddRange(vehicles);

您可能需要重新考虑为什么要这样做。这些课程有共同点吗?然后使用接口/基类选项。如果不是,将不同类型的对象添加到同一个列表的原因是什么?您实际尝试解决的问题可能与此问题无关。


推荐阅读