【问题标题】:C# -Converting a list of one class to list of another class with same properties [duplicate]C# - 将一个类的列表转换为具有相同属性的另一个类的列表[重复]
【发布时间】:2018-02-21 18:24:17
【问题描述】:

我有一个方法来返回一个类 A 的列表。但是我正在存储另一个具有相同属性的类的列表,并且需要返回这个类。

代码:

public List<Menu> GetAllMenus()
{
    Menu _menu = null;
    List<Menu> MenuList = new List<Menu>();
    List<Menu2> CacheMenuList=new List<Menu2>();
    //Caching
    string CacheKey = "GetAllMenus";
    ObjectCache cache = MemoryCache.Default;
    if (cache.Contains(CacheKey))
        CacheMenuList= (List<Menu2>)cache.Get(CacheKey);
    return CacheMenuList
}

Menu 和 Menu2 类型都具有相同的属性。 由于要求,我需要将其作为 Menu2 类型的另一个列表返回。 在上面的代码中,由于它是 Menu2 类型,因此无法返回 CacheMenuList。有没有其他方法我可以做到。我收到以下错误。

无法将类型“System.Collections.Generic.List”隐式转换为“System.Collections.Generic.List”DailyThanthi.Repository D:\Prjct\DTNewsRevamp\ DailyThanthi.Common\DailyThanthi.Repository\MenuRepository.cs 85 活动

【问题讨论】:

  • 您必须将Menu 类型的每个对象转换或转换为Menu2。查看“automapper”作为一种方式,或者只是编写代码来完成它。

标签: c# asp.net generics collections


【解决方案1】:

我建议为此使用优秀的库Automapper,如果属性完全相同,这应该特别容易。这是一个最小的工作示例:

Mapper.Initialize(cfg => cfg.CreateMap<Menu, Menu2>());

List<Destination> cacheMenuList = Mapper.Map<List<Menu>, List<Menu2>>(sources);

如果属性之间没有 1:1 映射,则必须在初始化映射器时调整配置。

阅读更多关于 Automapper 的一般信息 here 和关于映射集合的信息 here

【讨论】:

    【解决方案2】:

    这是一种方法:

    CacheMenuList= ((List<Menu>)cache.Get(CacheKey)).Select(
        x => new Menu2 () {
            Property1 = x.Property1,
            Property2 = x.Property2,
            Property3 = x.Property3,
            Property4 = x.Property4
        }
    ).ToList();
    

    您基本上为List&lt;Menu&gt; 中的每个Menu 对象创建一个Menu2 对象。您将每个Menu 属性分配给Menu2 中的相应属性。

    【讨论】:

    • 我不能这样做,因为我在另一个函数中将 List 设为 null。由于我得到错误值不能为空。参数名称:来源。所以我正在尝试我是否可以做到这一点
    【解决方案3】:

    创建一个接口并返回一个列表怎么样?

    public interface IMenu { ... }
    
    public class Menu : IMenu { ... }
    
    public class Menu2 : IMenu { ... }
    
    
    public List<IMenu> GetAllMenus()
        {
            List<IMenu> result = new List<Menu>();
            //Caching
            string CacheKey = "GetAllMenus";
            ObjectCache cache = MemoryCache.Default;
            if (cache.Contains(CacheKey))
                result= (List<IMenu>)cache.Get(CacheKey);
                return result;
    }
    

    或类似的东西。

    【讨论】:

      猜你喜欢
      • 2021-10-11
      • 2019-01-18
      • 1970-01-01
      • 2017-09-09
      • 2019-11-21
      • 1970-01-01
      • 2017-06-24
      • 2020-09-24
      • 1970-01-01
      相关资源
      最近更新 更多