【问题标题】:How to return distinct result in linq to collection如何将linq中的不同结果返回到集合
【发布时间】:2014-07-21 17:36:18
【问题描述】:
以下查询结果重复类代码。
cboFilterValues.DataSource = (From i In allDetails Select New LookUpItem With {.ItemText = i.ClassCode, .ItemValue = i.ClassCode} Distinct).ToList()
任何人都可以建议我如何为上述查询获得不同的结果。我需要将结果集设置为 IList(Of LookupItems)
谢谢
【问题讨论】:
标签:
vb.net
linq
linq-to-entities
linq-to-objects
【解决方案1】:
您的 Distinct 不起作用,因为(大概 - 您没有提供代码)您没有覆盖 LookUpItem 类中的 Equals 和 GetHashCode 方法,因此使用引用相等比较实例.如果您实现这些方法,则 Distinct 应该可以工作:
Public Overrides Function Equals(o As Object) As Boolean
If o Is Nothing OrElse Not Me.GetType().Equals(o.GetType()) Then Return False
Dim other = DirectCast(o, LookUpItem)
Return Me.ItemText = other.ItemText ' or some other fields
End Function
Public Overrides Function GetHashCode() As Integer
Return Me.ItemText.GetHashCode() ' or some other fields
End Function
或者,您可以稍微修改您的查询,因为您只使用来自allDetails 的ClassCode 属性,并将不同的地方放在那里(假设ClassCode 是String,或其他使用值相等):
cboFilterValues.DataSource = (
From i In (From d In allDetails Select d.ClassCode Distinct)
Select New LookUpItem With {.ItemText = i, .ItemValue = i}
).ToList()
【解决方案2】:
cboFilterValues.DataSource = (From x In (From i In allDetails Select i Distinct) Select New LookUpItem With {.ItemText = x.ClassCode, .ItemValue = x.ClassCode}).Tolist
我假设您上面的内容由于 select new 的一些问题而不起作用,如果这是问题,这应该解决它。
蒂姆