【问题标题】:Copy list of of objects to another list of another objects within another object将对象列表复制到另一个对象内的另一个对象列表
【发布时间】:2014-03-05 09:43:12
【问题描述】:

我的方法返回一个包含对象列表的响应对象。

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

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

}

我尝试过这样的事情,但我得到空引用异常:

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

请帮我解决问题。

【问题讨论】:

  • 你在哪一行得到这个
  • 看起来 lstAccnts 可能从调用 objRepo.GetAccountsFromRepo() 中返回 null。
  • res.Accounts = new List&lt;AccountsList&gt;(); res.Accounts.ForEach(c =&gt; c.AccountId = item.AccountId); 这两行没有意义。你创建 new List&lt;&gt;ForEach ?它总是有零个元素
  • @K.B 我在 res.Accounts.ForEach(c => c.AccountId = item.AccountId) 中出现错误;
  • @Baldrick 不,它正在返回帐户列表

标签: c# linq linq-to-objects


【解决方案1】:

这很明显,因为您只是在创建一个根本没有实例化对象的新列表 尝试这样的事情

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

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

    }

【讨论】:

  • 这也没有意义
  • 回答已编辑,现在看看为什么不从 lstAccnts 创建一个新列表并将项目添加到 res.Accounts
猜你喜欢
  • 2013-02-02
  • 2016-11-08
  • 1970-01-01
  • 1970-01-01
  • 2013-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多