LINQ 内部联接 - 从两个表返回

本文关键字:两个 返回 内部 LINQ | 更新日期: 2023-09-27 18:36:01

>我有以下查询

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"赋予不同的含义,"assoc"已经在"子"作用域中用于表示其他内容。

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

foreach (VaR 客户中的客户)

LINQ 内部联接 - 从两个表返回

为什么会有这一行:

select customer, assoc;

您是想退回客户、助理还是两者兼而有之? 假设是后者,您可以使用匿名类型组合它们:

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

然后,customers中的每个项目将有两个属性,CustomerAssoc,您可以从任何一个中获取所需的内容。

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

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