【问题标题】:Is there any Operator "LIKE" in the Observable Collection for filetringObservable Collection中是否有任何运算符“LIKE”用于过滤
【发布时间】:2014-10-06 21:24:38
【问题描述】:

是否可以像在 SQL 2014 中那样使用运算符 LIKE 来过滤 ObservableCollection。

前 SQL:SELECT * FROM Customer WHERE Name LIKE 'Cal%'

我需要相同类型的过滤,但使用 ObservableCollection,我知道你有来自 Linq 库的 Where,但它只查找 EXACT 字符串

谢谢

【问题讨论】:

  • 请记住,这些集合类可用于任何类型的元素。虽然有用于确定精确对应的标准化方法(参见IEquatableIComparable 接口),但没有用于检索任意类型的两个实例的“相似性”的标准化接口。因此,也没有这样的过滤方法;您必须根据您的自定义相似度测量来编写自己的代码。
  • .Where + .StartsWith().
  • .Where(str => str.StartsWith("Cal")) 你只需要在Where 子句中指定你的表达式
  • @Sunny 从您的ObservableCollection 创建ListCollectionView 并使用Filter 并绑定到它

标签: c# wpf linq observablecollection sql-server-2014


【解决方案1】:

为什么你说不能使用 Where over IObservableCollection ?

据我所知,您可以使用 Where(和其他 LINQ 方法): customers.Where(x=>x.StartsWith("Cal")); 会给你一个列表 如果你需要另一个 observable 集合,你必须用以前的结果重建一个新的集合:

var c = customers.Where(x=>x.StartsWith("Cal"));
customers = new ObservableCollection<Customer>(c.ToList());

根据你的需要,你也可以使用CollectionViewSource的“Filter”属性,具体使用方法见Filtering an ObservableCollection?

【讨论】:

  • IIRC .Where() 和其他 LINQ 方法返回 IEnumerable&lt;T&gt;,你必须 .ToList() 得到一个列表的结果
  • 好点,ObservableCollection 构造函数采用 List,而不是 IEnumerable。已在我的回答中修复。
【解决方案2】:

或者你可以使用CollectionView

IList<Employer> employers;
ICollectionView _employerView;
private string _filterString=string.Empty;

public Window1()    
{
   InitializeComponent();
    employers = GetCustomers();
   _employerView = CollectionViewSource.GetDefaultView(employers);
   _employerView.Filter = EmployerFilter;
   this.Loaded += new RoutedEventHandler(Window1_Loaded);
} 

public bool EmployerFilter(object item)
{
   Employer employer = item as Employer;
   return employer.Name.ToLower().StartsWith(_filterString.ToLower());
}

public string FilterString
{
   get { return _filterString; }
   set{
  _filterString = value; 
   OnPropertyChanged("FilterString");
  _employerView.Refresh();
}  }

【讨论】:

  • .Name.ToLower().StartsWith(_filterString.ToLower()); 相比,.Name.StartsWith(_filterString, StringComparison.OrdinalIgnoreCase) 将获得更好的性能,这将具有相同的比较效果。 (其实做StringComparison.CurrentCultureIgnoreCase是完全一样的效果,但是如果不需要具体的文化规则Ordinal会稍微快一些)
  • 感谢斯科特的提示。
【解决方案3】:

只有当您告诉它与 .Where(x=&gt;x.Equals("Cal")) 完全匹配时,Where 才会完全匹配,您可以通过切换到 StartsWith 来执行与 SQL 示例相同的操作。 .Where(x=&gt;x.StartsWith("Cal")).

【讨论】:

  • 谢谢大家,我不知道我可以直接在 WHERE 中做一个 startwith 非常感谢您的回答,真的很有帮助
猜你喜欢
  • 2016-12-02
  • 2012-10-16
  • 2020-05-18
  • 1970-01-01
  • 2020-01-28
  • 1970-01-01
  • 2011-08-27
  • 2021-08-08
  • 1970-01-01
相关资源
最近更新 更多