LINQ Inner Join - Return From Both Tables

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-13 16:16:17

问题


I have the following query

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# does not like the "assoc" at the end.

My error message is:

A local variable named 'assoc' cannot be declared in this scope because it would give a different meaning to 'assoc', which is already used in a 'child' scope to denote something else.

I need to return all columns from both table and then iterate with a

foreach (var customer in customers)


回答1:


Why do you have this line:

select customer, assoc;

Are you trying to return a customer, an assoc, or both? Assuming the latter, you can combine them using anonymous types:

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

Then each item in customers would have two properties, Customer and Assoc and you can grab what you need from either.




回答2:


You could wrap both of the items in an anonymous type.

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


来源:https://stackoverflow.com/questions/10823990/linq-inner-join-return-from-both-tables

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!