2012-12-06 77 views
-1

我是新來的LINQ,有人可以幫助我如何以下查詢轉換爲LINQ:內加入與LINQ

select c.cityname, c.cityid from country cn 
inner join [State] st on cn.stateid = st.stateid 
inner join [city] c on c.cityid = st.cityid where 
cn.countrid = 'cn001' order by c.cityname 
+0

看看這個問題(相關): http://stackoverflow.com/questions/37324/what-is-the-syntax-for-an-inner-join-in-linq-to-sql – Jens

+0

謝謝..我在找這個只要 – jestges

回答

0

試試這個:

List<State> States = new List<State>(); 
List<City> Cities = new List<City>(); 
List<Country> Countries = new List<Country>(); 

int countryId = 10; 
var query = Countries 
      .Join(States, c => c.StateId, s => s.StateId, (c, s) => new {Country = c, State = s}) 
      .Join(Cities, s => s.State.CityId, c => c.CityId, (t, c) => new {c.CityId, c.CityName, t.Country.CountryId}) 
      .Where(r => r.CountryId == countryId) 
      .Select(r => new {r.CityName, r.CityId}) 
      .OrderBy(r => r.CityName); 


class Country 
{ 
    public int StateId { get; set; } 

    public int CountryId { get; set; } 
} 
class State 
{ 
    public int StateId { get; set; } 

    public int CityId { get; set; } 
} 

class City 
{ 
    public int StateId { get; set; } 

    public int CityId { get; set; } 

    public string CityName { get; set; } 
}