【问题标题】:Remove Duplicates Linq Query Dropdownlist in VB.net在 VB.net 中删除重复的 Linq 查询下拉列表
【发布时间】:2014-09-25 13:54:36
【问题描述】:

我已将我的数据源绑定到下拉列表并且它可以工作,但它显示重复。这是我的代码

Private Sub ddlMasterPids_Load(sender As Object, e As EventArgs) Handles ddlMasterPids.Load
    Dim db As New DesignConstructionDataContext

    Dim Master = (From Master_Name In db.groups
                  Where (Master_Name.Master_Name IsNot Nothing)
                  Select Master_Name).ToList().Distinct()

    ddlMasterPids.DataSource = Master
    ddlMasterPids.DataTextField = "Master_Name"
    ddlMasterPids.DataValueField = "Master_Name"
    ddlMasterPids.DataBind()
End Sub

.Distinct() 不会抛出错误,但仍然存在重复。我也尝试切换 distinc 和 tolist,但仍然忽略了 distinct。有什么想法吗?

【问题讨论】:

  • 你为什么在ToList之后调用Distinct?这会在删除重复项之前将所有内容填充到内存中。而是让数据库跳过重复项。 Master_Name 到底是什么,String
  • Master_Name 是一个字符串,我尝试将 Distinct 放在 ToList 之前,但它也不起作用。

标签: sql asp.net vb.net linq


【解决方案1】:

您选择的不是Master_Name 列,而是Master_Name 表中的行。这就是为什么Distinct 不能按预期工作的原因。这些行至少有一列不同。

你想要的是这个:

Dim Master = (From Master_Name In db.groups
              Where Master_Name.Master_Name IsNot Nothing
              Select Master_Name.Master_Name).Distinct().ToList()

还要注意,我在ToList 之前调用Distinct 以过滤数据库中已经存在的内容。

【讨论】:

  • 嗯...我试过了,现在在DataBind() 给我一个错误说System.String does not contain a property with the name Master_Name
  • @kelseywhiting:我必须承认我并不真正理解您的问题。 Master_Name.Master_Name 是什么,Master_Name In db.groups 是什么?令人困惑的命名。
  • 我正在尝试获取位于Master_Name 列中的数据库中所有项目的下拉列表,我也刚刚将变量命名为 Master_Name。我希望列表跳过空值和重复项。我是 asp.net 的超级新手。我对 linq 和数据绑定有点困惑
  • @kelseywhiting 这很令人困惑。为了获得有用的答案,请重命名问题中的变量,以便其他人能够理解。
  • Tim 只为您选择了 Master_Name 列。您现在有了一个不同的 string 列表。您无需为数据绑定选择字段。删除DataSourceDataBind 之间的两行。
猜你喜欢
  • 2021-04-12
  • 2018-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-11
  • 1970-01-01
  • 2018-12-19
相关资源
最近更新 更多