Click here to Skip to main content
15,173,299 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How do we write self join in LINQ? I have tried this:
C#
from coa in GL0_ChartOfAccounts
  join c in GL0_ChartOfAccounts on coa.MainAccount equals c.ControlAccount into cs 
  from ca in cs.DefaultIfEmpty()
  select new 
  {
  	MainAccount = coa.MainAccount, 
	Title = coa.Title, 
	ControlLevel = coa.ControlLevel, 
	ControlAccount = coa.ControlAccount, 
	ControlTitle = ca.Title
	}
Unfortunately, this gives an anonymous type error.

To clarify this, suppose there are three columns:
MainAccount 
Title
ParentAccount
Now I want to get title or name of account instead of ParentAccount(int) how should I write this in LINQ?
Posted
Updated 28-Jan-14 0:47am
v3
Comments
EduChapow 28-Jan-14 8:55am
   
You can see somes examples right here:
http://code.msdn.microsoft.com/LINQ-Join-Operators-dabef4e9

var q = (from coa in Glochartofaccount
join c in Glochartofaccount on coamainaccount equals c controlaccount
select new
{
MainAccount = coa.MainAccount,
Title = coa.Title,
ControlLevel = coa.ControlLevel,
ControlAccount = coa.ControlAccount,
ControlTitle = ca.Title
).FirstOrDefault();
   
v2
try by using this sample..

C#
List<employee> emp = new List<employee>();
emp.Add(new Employee()
{
    EmpID = 1,
    EmpName = "a",
    City = "Pune",
    ManagerID = 11
});

emp.Add(new Employee()
{
    EmpID = 2,
    EmpName = "b",
    City = "mumbai",
    ManagerID = 12
});

emp.Add(new Employee()
{
    EmpID = 3,
    EmpName = "c",
    City = "Pune",
    ManagerID = 2
});

emp.Add(new Employee()
{
    EmpID = 4,
    EmpName = "d",
    City = "Delhi",
    ManagerID = 14
});

//----Linq query

var q = (from employee in emp
        join employee2 in emp on employee.EmpID equals employee2.ManagerID
        select employee).FirstOrDefault();
</employee></employee>
   
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900