0

我尝试从 tblAccomodation 获取所有邮政编码的列表以放入组合框中。

例如
8630 - Veurne
8660 - De Panne
8670 - Koksijde

这是两张表之间的关系: 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;
}

我需要改变什么?

4

2 回答 2

1

Distinct比较oAccomodation对象,你需要的是 CityID 的比较

您可以使用morelinqDistinctBy,因为您已经AllAccomodations在内存中。

foreach (tblAccomodation item in AllAccomodations.DistinctBy(x=>x.CityID))

或者

foreach (tblAccomodation item in AllAccomodations.GroupBy(x => x.CityID)
                                                 .Select(g => g.First()))
于 2012-08-24T09:28:03.200 回答
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;
    }
于 2012-08-24T09:36:11.167 回答