You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LINQ查询未生成预期结果:WinForm下拉框联动问题求助

WinForm中ComboBox联动填充问题排查与解决

我刚接触LINQ,尝试将WinForm中一个ComboBox(选择位置类型,比如“Hometown”)的结果用于填充另一个ComboBox,但点击目标ComboBox时无任何内容显示。目标下拉框应根据选择的类型显示对应内容,比如选“Hometown”时显示圣安东尼奥这类家乡名称。

初始错误代码

private void LocationComboBox_DropDown(object sender, EventArgs e)
{
    if (!string.IsNullOrEmpty(lastNameTextBox.Text))
    {                
        using PersonsContext dbContext = new PersonsContext();
        List<string?> filteredResults = new List<string?>();

        var tempResults = dbContext.Persons
            .Where(a => EF.Functions.Collate(a.LastName, "NOCASE") == lastNameTextBox.Text)
            .GetType()
            .GetProperties()
            .Where(a => a.Name == locationTypeComboBox.Text)
            .Select(a => a.GetValue(a, null)).FirstOrDefault();
        if (tempResults != null) 
        {
           
            filteredResults.Add(tempResults.ToString());
            filteredResults.Sort();
            filteredResults = filteredResults.Distinct().ToList();
            locationComboBox.Items.Clear();
            locationComboBox.Items.AddRange([.. filteredResults]);
            locationComboBox.Items.Remove(String.Empty);
        }                
    }
    else
    {
        // todo:
    }
}

初始代码问题分析

  • 错误对IQueryable<Person>执行.GetType().GetProperties(),获取的是IQueryable类型自身的属性,而非Person实体类的属性,完全偏离了获取目标字段的初衷
  • GetValue(a, null)参数逻辑混乱,导致tempResults始终为null,无法向下拉框添加任何内容

修正后可运行代码

参考@Fildor提供的示例调整后,代码可正常实现联动功能:

private void LocationComboBox_DropDown(object sender, EventArgs e)
{
    if (!string.IsNullOrEmpty(lastNameTextBox.Text))
    {
        var projections = new Dictionary<string, Func<Person, object?>>()
        {
            [nameof(Person.LastName)] = p => p.LastName,
            [nameof(Person.Hometown)] = p => p.Hometown,
            [nameof(Person.County)] = p => p.County,
            [nameof(Person.State)] = p => p.State,
            [nameof(Person.Country)] = p => p.Country
        };
        
        var projection = projections[locationTypeComboBox.Text];
        
        using PersonsContext dbContext = new PersonsContext();
     
        var filteredResults = dbContext.Persons
            .Where(a => EF.Functions.Collate(a.LastName, "NOCASE") == lastNameTextBox.Text)
            .Select(projection)
            .ToList();

        filteredResults.Sort();
        filteredResults = filteredResults.Distinct().ToList();
        locationComboBox.Items.Clear();
        locationComboBox.Items.AddRange([.. filteredResults]);
        locationComboBox.Items.Remove(String.Empty);
    }                
    else
    {
        // todo:
    }
}

再次感谢各位的帮助!

内容的提问来源于stack exchange,提问作者user17484004

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 10:27:48