2014-03-05 223 views
0

我的方法返回一個包含對象列表的響應對象。將對象列表複製到另一個對象中另一個對象的另一個列表中

public class GetAccountsListResponse 
{ 
    public List<AccountsList> Accounts { get; set; } 
} 

public class AccountsList 
{ 
    public string AccountId { get; set; } 
    public string AccountName { get; set; } 

} 

我想這樣的事情,但即時得到空refernce例外:

public GetAccountsListResponse GetAccountsList() 
    { 

     AccountRepository objRepo = new AccountRepository(); 
     GetAccountsListResponse res = new GetAccountsListResponse(); 

     List<Account> lstAccnts = new List<Account>(); 
     lstAccnts = objRepo.GetAccountsFromRepo(); 

     foreach (var item in lstAccnts) 
     { 
      res.Accounts = new List<AccountsList>(); 
      res.Accounts.ForEach(c => c.AccountId = item.AccountId);  

     } 

     return res; 
    } 

請幫我解決這個問題。

+0

在哪一行,你收到此 –

+0

貌似lstAccnts *力量*趕回來空的調用'objRepo.GetAccountsFromRepo()'。 – Baldrick

+2

'res.Accounts = new List (); res.Accounts.ForEach(c => c.AccountId = item.AccountId);'這兩行沒有意義。你創建'新的List <>'和'ForEach'?它將始終有零元素 –

回答

3

這是顯而易見的,你只創建一個沒有在所有 實例化對象的新列表嘗試這樣的事情

res.Accounts = new List<AccountsList>(); 
    foreach (var item in lstAccnts) 
    { 

     res.Accounts.Add(new AccountsList(){AccountId =item.AccountId});  

    } 
+0

這也沒有意義 –

+0

回答編輯現在看看爲什麼不這樣做會從lstAccnts創建一個新列表並添加項目到res.Accounts –

+0

謝謝你的工作。我如何使用LINQ來做到這一點? – Imp

相關問題