C# - 将一个类的列表转换为具有相同属性的另一个类的列表

时间:2017-09-13 06:54:58

标签: c# asp.net generics collections

我有一个返回类A列表的方法。但是我存储了具有相同属性的另一个类的List,需要返回此类。

代码:

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&lt; DailyThanthi.Contracts.Menu2&gt;'到'System.Collections.Generic.List&lt; DailyThanthi.Contracts.Menu&gt;' DailyThanthi.Repository D:\ Prjct \ DTNewsRevamp \ DailyThanthi.Common \ DailyThanthi.Repository \ MenuRepository.cs 85 Active

3 个答案:

答案 0 :(得分:3)

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

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

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

如果属性不相互映射1:1,则必须在初始化映射器时调整配置。

详细了解Automapper here以及地图集合here

答案 1 :(得分:1)

以下是一种方法:

 t.printStackTrace();
 }

您基本上为CacheMenuList= ((List<Menu>)cache.Get(CacheKey)).Select( x => new Menu2 () { Property1 = x.Property1, Property2 = x.Property2, Property3 = x.Property3, Property4 = x.Property4 } ).ToList(); 中的每个Menu2对象创建了一个Menu对象。您将每个List<Menu>属性分配给Menu中的相应属性。

答案 2 :(得分:1)

如何创建界面并返回其中的列表?

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;
}

或类似的东西。

相关问题