我有一个 ObservableCollection<DateTime> myItems
里面有一些需要被删除的重复项
我尝试使用以下方法进行去重:
myItems = myItems.Distinct();
然而我无法构建它并收到以下错误:
Error 1 Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'System.Collections.ObjectModel.ObservableCollection'. An explicit conversion exists (are you missing a cast?)
当我检查ObservableCollection时,我发现它是如下Go to Definition所示的IEnumerable<T>格式:
public class ObservableCollection<T> : Collection<T>, INotifyCollectionChanged, INotifyPropertyChanged
public class Collection<T> : IList<T>, ICollection<T>, IReadOnlyList<T>, IReadOnlyCollection<T>, IEnumerable<T>, IList, ICollection, IEnumerable
所以我尝试如下转换:
myItems = (ObservableCollection<DateTime>) myItems.Distinct();
编译没有错误,但运行时会抛出以下错误:
类型“System.InvalidCastException”的异常在 mscorlib.ni.dll 中发生,但未在用户代码中处理。其他信息:无法将类型为 'd__81<code>1[System.DateTime]' 的对象强制转换为类型 'System.Collections.ObjectModel.ObservableCollection</code>1[System.DateTime]'。
我还尝试了以下:
myItems = (ObservableCollection<DateTime>) myItems.Distinct().toList<DateTime>();
但是我收到了以下的编译时错误:
Error 1 无法将类型'System.Collections.Generic.List'转换为类型'System.Collections.ObjectModel.ObservableCollection'
我错过了什么? 我该如何从ObservableCollection中删除重复项?
IEnumerable
构造函数投射一个新的可观察集合:https://dev59.com/lHA65IYBdhLWcg3w7DT8 - StuartLC