Search code examples
c#linqbackend

How to convert linq query with joins to method syntax?


I want to change this to lambda query in c#

var innerJoinTasinmaz = 
                from tasin in _context.Tasinmaz
                join mahalle in _context.Mahalle on tasin.MahalleID equals mahalle.AreaID
                join ilce in _context.Ilce on  tasin.CountyID equals ilce.CountyID
                join il in _context.Il on tasin.CityID equals il.CityID
                select new{
                    tasinmazID  = tasin.TasinmazID,
                    cityName    = il.CityName,
                    countyName  = ilce.CountyName,
                    areaName    = mahalle.AreaName,
                    ada         = tasin.Ada,
                    parsel      = tasin.Parsel,
                    nitelik     = tasin.Nitelik,
                    adres       = tasin.Adres,
                    isActive    = tasin.isActive,
            };

I am struggling to write it in Lambda Expression. Any help would be greatly appreciated.


Solution

  • You'll need the Join method which takes four parameters:

    1. the enumerable that you want to join
    2. a selector in the first enumerable
    3. a selector in the second enumerable
    4. a selector for both enumerables

    It is compared whether the values from 2 und 3 are the same, and if so, the selector from 4 is used to choose which properties you want to use. In your example, it would look like:

    var innerJoinTasinmaz =
        _context.Tasinmaz
            .Join(_context.Mahalle, x => x.MahalleId, y => y.AreaID, (x, y) => new { tasin = x, mahalle = y })
            .Join(_context.Ilce, x => x.tasin.CountyID, y => y.CountyId, (x, y) => new { tasin = x.tasin, mahalle = x.mahalle, ilce = y })
            .Join(_context.Il, x => x.tasin.CityId, y => y.CityId, (x, y) => new
            {
                tasinmazId = x.tasin.TasinmazID,
                cityName = y.CityName,
                countyName = x.ilce.CountyName,
                areaName = x.mahalle.AreaName,
                ada = x.tasin.Ada,
                parsel = x.tasin.Parsel,
                nitelik = x.tasin.Nitelik,
                adres = x.tasin.Adres,
                isActive = x.tasin.isActive,
            });
    

    You can think about whether method or query syntax is more readable.