使用lambda表达式设置组合框数据源c#windows Forms应用程序

时间:2017-10-09 16:55:01

标签: c# lambda combobox datasource

给出以下实例变量

        cboBankAccountId.DataSource = db.BankAccounts.Where(x => x.BankAccountId).ToList();

让我们假设我的表名和属性都是正确的......有人可以向我解释为什么这种分配数据源的方式不适用于Windows窗体应用程序。

但我在其他帖子中看到以下内容(以及我在项目中使用的内容)的作用 现在这只是因为如何在Windows窗体和Web窗体中分配组合框属性??

cboBankAccountId = db.BankAccounts;
cboBankAccountId.ValueMember = "BankAccountId";
cboBankAccountId.DisplayMember = "FullName";

...谢谢 感恩节快乐!

1 个答案:

答案 0 :(得分:0)

ComboBox控件的数据源可以是数据库,Web服务或稍后可用于生成数据绑定控件的对象。

代码的问题在于lambda表达式。 您的案例中的扩展方法“Where”需要类型为Func<BankAccounts, bool>的委托。即,您必须传递一个以BankAccounts作为输入的委托,并将bool作为输出,用于过滤您的结果。

所以,如果你想找出ID为1的BankAccounts,你的lambda表达式将如下所示:

cboBankAccountId.DataSource = db.BankAccounts.Where(x => x.BankAccountId == 1).ToList();

如果您不熟悉Lambda Expressions,还可以将其翻译为:

cboBankAccountId.DataSource = db.BankAccounts.Where((BankAccounts x) =>
{
    return x.BankAccountId == 1;
}).ToList();

或者,完整版:

public bool Filter(BankAccountId id)
{
     bool filterPassed;

     if(id == 1)
         filterPassed = true;
     else
         filterPassed = false;  

     return filterPassed;
}
cboBankAccountId.DataSource = db.BankAccounts.Where(Filter).ToList();

如您所见,您需要传递给Where方法的所有方法都可以用于过滤结果。然后,列表中的每个项目都将通过此方法运行,并且仅返回通过测试的项目。这就是LINQ中Where扩展方法的工作方式。