【问题标题】:LINQ Inner Join - Return From Both TablesLINQ 内连接 - 从两个表返回
【发布时间】:2012-06-05 03:25:57
【问题描述】:

我有以下问题

var customers = from customer in context.tblAccounts 
                join assoc in context.tblAccountAssociations on customer.AccountCode equals assoc.ChildCode 
                where customer.AccountType == "S" || customer.AccountType == "P" 
                select customer, assoc;

C# 不喜欢末尾的“assoc”。

我的错误信息是:

不能在此范围内声明名为“assoc”的局部变量,因为它会给“assoc”赋予不同的含义,后者已在“子”范围内用于表示其他内容。

我需要从两个表中返回所有列,然后使用

foreach(客户中的客户变量)

【问题讨论】:

  • 难道你不能……更改变量的名称吗?
  • 您需要返回 2 个单独的对象还是需要填充客户对象的属性?

标签: c# linq inner-join


【解决方案1】:

为什么会有这行:

select customer, assoc;

您是要退回客户、副总裁,还是两者兼而有之?假设是后者,您可以使用匿名类型将它们组合起来:

select new { Customer = customer, Assoc = assoc };

那么customers 中的每个项目都有两个属性,CustomerAssoc,您可以从中获取所需的内容。

【讨论】:

    【解决方案2】:

    您可以将这两个项目都包装在匿名类型中。

    var customers = from customer in context.tblAccounts 
                join assoc in context.tblAccountAssociations on customer.AccountCode equals assoc.ChildCode 
                where customer.AccountType == "S" || customer.AccountType == "P" 
                select new {customer, assoc};
    

    【讨论】:

      猜你喜欢
      • 2015-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-28
      • 2015-04-23
      • 2014-11-05
      相关资源
      最近更新 更多