2017-09-13 43 views
-1

我有一個方法來返回類A的列表。但我存儲具有相同屬性的另一個類的列表,並且需要返回此類。C# - 將一個類的列表轉換爲具有相同屬性的另一個類的列表

代碼:

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 
} 

這兩種類型的菜單和菜單2具有相同的屬性。 由於需求我需要將它作爲Menu2類型的另一個列表返回。 在上面的代碼中,因爲它是Menu2類型,所以不能返回CacheMenuList。有沒有其他辦法可以做到這一點。我收到以下錯誤。

無法隱式轉換類型 'System.Collections.Generic.List < DailyThanthi.Contracts.Menu2>' 到 'System.Collections.Generic.List < DailyThanthi.Contracts.Menu>' DailyThanthi.Repository d:\ PRJCT \ DTNewsRevamp \ DailyThanthi.Common \ DailyThanthi.Repository \ MenuRepository.cs 85主動

+2

您將不得不將每個「Menu」類型的對象都轉換或轉換爲「Menu2」。查看「automapper」作爲一種方式,或者只是寫代碼來做到這一點。 –

回答

1

下面是做這件事:

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財產分配給Menu2中的相應財產。

+0

我不能這樣做,因爲我在另一個函數中將列表

設置爲null。由於我得到的錯誤值不能爲空。參數名稱:來源。所以我正在嘗試是否有辦法做到這一點 –

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

如何創建一個接口並返回它的列表?

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

或類似的東西。

相關問題