linq中的查询子集

时间:2015-11-11 12:35:24

标签: c# linq model-view-controller

我想执行链接查询,看起来像这样 我已经给了大陆ID,基于此,我选择了一个:

    var continent = db.Continent.FirstOrDefault(c => c.Id == Continent_Id);

然后我想找到来自特定大陆的国家子集。 然后,我想根据国家/地区ID找到来自特定国家/地区的城市子集。任何想法如何做到这一点? 这些是我的课程:

public class Contient
{
public int Id { get; set; }
public string Name { get; set; }
}   

public class Country
{
public int Id { get; set; }
public string Name { get; set; }
public int ContientId { get; set; }
}
 public class City
{
public int Id { get; set; }
public string Name { get; set; }
public int CountryId { get; set; }
}

2 个答案:

答案 0 :(得分:1)

首先,您需要在模型中添加一些navigation properties

public class Continent
{
  public int Id { get; set; }
  public string Name { get; set; }

  public virtual ICollection<Country> Country{get;set;}//Add this property
}   

public class Country
{
  public int Id { get; set; }
  public string Name { get; set; }
  public int ContinentId { get; set; }

  public virtual Continent Continent{get;set;}//Add this property
  public virtual ICollection<City> Cities{get;set;}//Add this property
}
public class City
{
  public int Id { get; set; }
  public string Name { get; set; }
  public int CountryId { get; set; }
  public virtual Country Country{get;set;}//Add this property
}

然后你可以运行这样的查询:

var countries= db.Countries.Where(c=>c.ContinentId==Continent_Id);
var cities= countries.SelectMany(c=>c.Cities);

而且,如果您已经拥有该大陆,您也可以这样做:

  var continent = db.Continent.FirstOrDefault(c => c.Id == Continent_Id);
  var countries= continent.Countries;
  var cities= countries.SelectMany(c=>c.Cities);

SelectMany扩展方法会将与每个国家/地区相关的城市展平为一个序列。

更新

我将告诉您如何在不使用查询中的导航属性的情况下执行相同的操作,但我仍然建议您将它们添加到模型中:

var continent = db.Continent.FirstOrDefault(c => c.Id == Continent_Id);
var countries=  db.Countries.Where(c=>c.ContinentId==Continent_Id);
var countriesId=countries.Select(c=>c.Id).ToList();
var cities= db.Cities.Where(c=>countriesId.Contains(c.CountryId));

答案 1 :(得分:0)

假设你有类似的东西

Continent[] continents; 
Country[] countries; 
City[] cities;
(...)
int continentId=5; //just a example

在代码中的某处,这就足够了:

LINQ查询:

//Getting Continent
var quContinents = from continent
                   in continents
                   where country.Id == continentId 
                   select continent

//Getting Countries from Continent
var quCountries = from country
                  in countries
                  where country.continentID == continentId
                  select country

//go trough all countries which as been found
foreach(var country in quCountries)
{
  var quCities = from city
                 in cities
                 where city.countryID == country.Id
                 select city
  //display cities
  foreach (var city in quCities)
    Console.WriteLine(city.Name " in " country.Name);
}