我尝试从tblAccomodation获取所有Zipcodes的列表以放入组合框。
e.g。
8630 - Veurne
8660 - De Panne
8670 - 科克赛德
这是两个表之间的关系: tblCity.ID = tblAccomodation.CityID
TblCity包含(ID,Zipcode,Name,UpName,StructCode) TblAccomodation包含(ID,CityID,Name,.....)
当然,有多个住宿使用相同的CityID,所以我尝试使用DISTINCT()。但它不起作用。
public static Dictionary<int, string> getPostals()
{
Dictionary<int, string> Zipcodes = new Dictionary<int, string>();
var AllAccomodations = (from oAccomodation in new DBReservationDataContext().tblAccomodations
orderby oAccomodation.Name ascending
select oAccomodation).ToList();
foreach (tblAccomodation item in AllAccomodations.Distinct())
{
Zipcodes.Add(item.CityID, clsCities.getCityInfo(item.CityID, "Zipcode") + ' ' + clsCities.getCityInfo(item.CityID, "UpName"));
}
return Zipcodes;
}
我需要改变什么?
答案 0 :(得分:1)
Distinct
比较oAccomodation
个对象,你需要的是CityID的比较
您可以使用morelinq的DistinctBy,因为您已在内存中拥有AllAccomodations
。
foreach (tblAccomodation item in AllAccomodations.DistinctBy(x=>x.CityID))
或
foreach (tblAccomodation item in AllAccomodations.GroupBy(x => x.CityID)
.Select(g => g.First()))
答案 1 :(得分:0)
public static Dictionary<int, string> getPostals()
{
Dictionary<int, string> oZipcodes = new Dictionary<int, string>();
DBReservationDataContext oDBConnection = new DBReservationDataContext();
var vAllCities = (from oCity in oDBConnection.tblCities
where (from oAccomodation in oDBConnection.tblAccomodations
select oAccomodation.CityID).Contains(oCity.ID)
select oCity).Distinct();
foreach (tblCity item in vAllCities)
{
oZipcodes.Add(item.ID, clsCities.getCityInfo(item.ID, "Zipcode") + ' ' + clsCities.getCityInfo(item.ID, "UpName"));
}
return oZipcodes;
}