在返回的一个字段上选择distinct

时间:2011-06-29 03:26:52

标签: linq

我试图返回一个不同的列表 - 但是不是在所有返回的字段上投射Distinct()运算符,我只希望Suburb将运算符应用于它,就像lga.Suburb.Distinct()一样,但这样做不工作 - 我该怎么做?

谢谢!

Public Function GetLGAForRegion(ByVal region As Integer)

    Dim dc As New DataContextDataContext
    Dim query = (From lga In dc.tblLGA_Suburbs
    Join suburb In dc.tblSuburbs On lga.Suburb Equals suburb.SuburbName
    Join regions In dc.tblRegions On suburb.RegionID Equals regions.RegionID
    Where (regions.RegionID = region)
    Select lga.Suburb.Distinct(), suburb.SuburbID).ToList()
    Return query

End Function

好的 - 这很有效:)感谢您的帮助!

 Dim query = (From lga In dc.tblLGA_Suburbs
        Join suburb In dc.tblSuburbs On lga.Suburb Equals suburb.SuburbName
        Join regions In dc.tblRegions On suburb.RegionID Equals regions.RegionID
        Where (regions.RegionID = region)
        Group By lga = lga.Suburb Into g = Group
        Order By lga Ascending
        Select g.First().lga.Suburb, g.First().suburb.SuburbID).ToList()

1 个答案:

答案 0 :(得分:2)

您可以像这样使用GroupBy

GroupBy(r -> r.Suburb).Select(g => g.First())
查询样式中的

Dim query = (From lga In dc.tblLGA_Suburbs
Join suburb In dc.tblSuburbs On lga.Suburb Equals suburb.SuburbName
Join regions In dc.tblRegions On suburb.RegionID Equals regions.RegionID
Where (regions.RegionID = region)
Group lga by lga.Suburb into suburbGroup
Select suburbGroup.First();