c# - 无法将类型 'System.Collections.Generic.List<AnonymousType#1>' 隐式转换为 'System.Collections.Generic.List<Model.tblLaborBankAccount>'

标签 c# linq generics

我在返回列表时遇到问题, 这是我的代码:

    public List<tblLaborBankAccount> ListAllLaborBankAccountByLaborID (int laborID)
    {
        var result = (from b in context.tblBankNames
                      join c in context.tblLaborBankAccounts
                      on b.bknBankNameID equals c.bknBankNameID
                      where c.lbrLaborID == laborID
                      select (new { c, b })
                              ).ToList();

        return result;
    }

并且 result 返回一个匿名类型,因为我正在返回一个连接查询并且返回类型不再是 tblLaborBankAccount

我应该为这个匿名类型创建一个新类还是有更好的方法?

谢谢。

最佳答案

select 语句是一个创建匿名类的投影。

匿名类可以在方法中使用,但不能作为结果返回。

你可以返回一个 List<Tuple<tblBankName, tblLaborBankAccount>>像这样:

public List<Tuple<tblBankName, tblLaborBankAccount>> ListAllLaborBankAccountByLaborID (int laborID)
{
    var result = (from b in context.tblBankNames
                  join c in context.tblLaborBankAccounts
                  on b.bknBankNameID equals c.bknBankNameID
                  where c.lbrLaborID == laborID
                  select (new Tuple<tblBankName, tblLaborBankAccount>( c, b ))
                          ).ToList();

    return result;
}

或者您可以声明一个结构/类来包含您的结果:

public class BankAccountDetails
{
     public tblBankName BankName {get;set;}
     public tblLaborBankAccount BankAccount {get;set;}
}

然后返回它们的列表:

public List<BankAccountDetails> ListAllLaborBankAccountByLaborID (int laborID)
{
    var result = (from b in context.tblBankNames
                  join c in context.tblLaborBankAccounts
                  on b.bknBankNameID equals c.bknBankNameID
                  where c.lbrLaborID == laborID
                  select (new BankAccountDetails{ BankName =  c, BankAccount =  b })
                          ).ToList();

    return result;
}

关于c# - 无法将类型 'System.Collections.Generic.List<AnonymousType#1>' 隐式转换为 'System.Collections.Generic.List<Model.tblLaborBankAccount>',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25339337/

相关文章:

c# - 从excel中排序列表

c# - 表示双引号的更简洁的方式?

UserControl 的自定义 Text 属性的 C# 自定义 TextChanged 事件处理程序?

c# - 将多个连续的相等字符从一个字符串减少为一个

java - 如何创建根据 T 表现不同的通用方法?

c# - 接口(interface)的 ContractInvariant 方法

.net - 存储库是否应该实现 IQueryable<T>?

c# - 通过动态属性将两个通用列表相交

java - 将接口(interface)列表转换为具体类型列表

java - 在方法参数中使用通配符