【问题标题】:Combobox "Select All" in linq querylinq查询中的组合框“全选”
【发布时间】:2013-08-11 19:05:51
【问题描述】:

我有多个组合框将值传递给 linq 查询。以前我是用

    if(combobox.text == "select all")
       {combobox.text = "")

然后使用 StartsWith(combobox.text) 方法进行比较,我知道这是错误的。因为“jim”会返回“Jimmy”。选择“全选”时如何全选?

【问题讨论】:

标签: winforms linq combobox


【解决方案1】:

最好有条件地添加查询过滤器:

var query = dataSource.foo.AsQueryable();
//you may or may not need AsQueryable() depending on what "foo" is
//if it is not queryable, you may need AsEnumerable(), or simply nothing

if (!combobox.Text.Equals("select all"))
    query = query.Where(x => x.Equals(combobox.Text));

return query.ToList();

“更简单”的方法是使用布尔值or,但生成的查询更难看,可能会也可能不会翻译成 SQL(如果您正在使用的话):

var query = dataSource.foo
    .Where(x => combobox.Text.Equals("select all") || x.Equals(combobox.Text));

【讨论】:

  • 这就是我认为它会来的,希望有一个更简单的方法。
  • 我已经演示了“更简单”的方式,使用 or 表达式,但它可能不是更好的选择,除非您知道优化器会删除多余的比较
  • 想了想,想出了一个懒惰的方法,它应该在 99.9999% 的时间里都有效 StartsWith() && EndsWith()
  • @user2525463 使用 Linq to SQL 时要小心,因为 EndsWith 不能使用索引。
  • @Ic 使用 Linq to xml
猜你喜欢
  • 2015-10-02
  • 2011-05-05
  • 1970-01-01
  • 2016-02-27
  • 2016-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多