C# 是否有接线员;例如;在FileString的可观察集合中

C# 是否有接线员;例如;在FileString的可观察集合中,c#,wpf,linq,observablecollection,sql-server-2014,C#,Wpf,Linq,Observablecollection,Sql Server 2014,是否可以使用类似于SQL 2014的运算符来过滤ObservableCollection Ex SQL:从客户中选择*名称,如“Cal%” 我需要相同类型的过滤,但对于ObservaleCollection,我知道您有Linq库中的Where,但它只查找精确的字符串 感谢当您告诉它与精确匹配时,它才与精确匹配。其中(x=>x.Equals(“Cal”),您可以通过切换到StartsWith来执行与SQL示例相同的操作.Where(x=>x.StartsWith(“Cal”))为什么你说你不能使用

是否可以使用类似于SQL 2014的运算符来过滤ObservableCollection

Ex SQL:
从客户中选择*名称,如“Cal%”

我需要相同类型的过滤,但对于ObservaleCollection,我知道您有Linq库中的Where,但它只查找精确的字符串


感谢当您告诉它与
精确匹配时,它才与精确匹配。其中(x=>x.Equals(“Cal”)
,您可以通过切换到StartsWith来执行与SQL示例相同的操作
.Where(x=>x.StartsWith(“Cal”))

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

据我记忆所及,您可以使用Where(和其他LINQ方法):
customers.Where(x=>x.StartsWith(“Cal”)将返回一个列表
如果需要返回另一个可观察集合,则必须使用以前的结果重建一个新集合:

var c = customers.Where(x=>x.StartsWith("Cal"));
customers = new ObservableCollection<Customer>(c.ToList());
var c=customers.Where(x=>x.StartsWith(“Cal”);
客户=新的可观察收集(c.ToList());
根据您的需要,您还可以使用CollectionViewSource的“Filter”属性,请参见有关如何使用它的示例。

或者您可以使用

IList雇主;
ICollectionView\u employerView;
私有字符串_filterString=string.Empty;
公共窗口1()
{
初始化组件();
雇主=获取客户();
_employerView=CollectionViewSource.GetDefaultView(雇主);
_employerView.Filter=EmployerFilter;
this.Loaded+=新路由EventHandler(Window1\u已加载);
} 
公共布尔值EmployerFilter(对象项)
{
雇主=作为雇主的项目;
返回employer.Name.ToLower().StartsWith(_filterString.ToLower());
}
公共字符串筛选器字符串
{
获取{return\u filterString;}
设置{
_filterString=值;
OnPropertyChanged(“FilterString”);
_employerView.Refresh();
}  }

请记住,这些集合类可用于任何类型的元素。虽然有确定精确对应关系的标准化方法(参见
IEquatable
IComparable
接口),但没有用于检索任意类型两个实例的“相似性”的标准化接口。因此,也没有这种过滤方法;您必须根据自定义的相似性度量编写自己的代码。
.Where
+
.StartsWith()
.Where(str=>str.StartsWith(“Cal”))
您只需在
Where
条款中指定表达式从
ObservableCollection
中可能重复的@Sunny create
ListCollectionView
,然后使用并绑定到该IIRC
。Where()
和其他LINQ方法返回
IEnumerable
,您必须
。ToList()
结果要有一个ListGood point,ObservableCollection构造函数需要一个列表,而不是一个IEnumerable。在我的回答中修复了。而不是使用(_filterString.ToLower())执行
.Name.ToLower().StartsWith
使用
.Name.StartsWith(_filterString,StringComparison.OrdinalIgnoreCase)
将获得更好的性能,这将具有相同的比较效果。(实际上做
StringComparison.CurrentCultureInoRecase
的效果完全一样,但是如果你不需要特定的文化规则,Ordinal会稍微快一点)谢谢你的提示Scott。谢谢大家,我不知道我可以直接在里面做startwith,非常感谢你的回答,真的很有帮助
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();
}  }