dorkboy
dorkboy

Reputation: 477

LINQ Inner Join - Return From Both Tables

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)

Upvotes: 2

Views: 5232

Answers (2)

Jason C
Jason C

Reputation: 152

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

Upvotes: 1

Kirk Woll
Kirk Woll

Reputation: 77596

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.

Upvotes: 8

Related Questions