Converting SQL Query into Linq (c#) with Distinct

csh*_*oob 1 c# sql linq linq-to-entities entity-framework

I am trying to write my SQL Statement with Linq, but I don't quite get it. I know there are many familiar posts, but maybe you can help me with mine and help me to understand how it works.

My SQL Query:

SELECT DISTINCT(cou.Country1) AS Laender, COUNT(cou.Country1) AS Anzahl FROM SEC_User be
INNER JOIN PAR_Company com ON com.CompanyID = be.CompanyID
INNER JOIN DAT_Country cou ON cou.CountryID = com.CountryID
Group by cou.Country1
Run Code Online (Sandbox Code Playgroud)

I think my start might be right:

var query = from user in db.SEC_User
join com in db.PAR_Company on user.CompanyID equals com.CompanyID
join cou in db.DAT_Country on com.CountryID equals cou.CountryID
Run Code Online (Sandbox Code Playgroud)

Thanks in advance!

Ser*_*lan 5

you can try this. you don't need DISTINCT with group by. group by makes already it distinct.

var query = from user in db.SEC_User
join com in db.PAR_Company on user.CompanyID equals com.CompanyID
join cou in db.DAT_Country on com.CountryID equals cou.CountryID
group cou by user.Country1 into g
select new { Laender = g.Key, Anzahl = g.Count()};
Run Code Online (Sandbox Code Playgroud)