I have an ObservableCollection<DateTime> myItems
and it has some duplicate items that needs to be removed
I tried using :
myItems = myItems.Distinct();
however i can't build it and recieve this error:
Error 1 Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'System.Collections.ObjectModel.ObservableCollection'. An explicit conversion exists (are you missing a cast?)
and when I check the ObservableCollection I find that it is IEnumerable<T>
as the following Go to Definition shows:
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
so I tried to cast as following :
myItems = (ObservableCollection<DateTime>) myItems.Distinct();
it build fine without error; but at runtime it throws the following error:
An exception of type 'System.InvalidCastException' occurred in mscorlib.ni.dll but was not handled in user code Additional information: Unable to cast object of type 'd__81
1[System.DateTime]' to type 'System.Collections.ObjectModel.ObservableCollection
1[System.DateTime]'.
I also tried the following:
myItems = (ObservableCollection<DateTime>) myItems.Distinct().toList<DateTime>();
but then I reeive the following compile time error:
Error 1 Cannot convert type 'System.Collections.Generic.List' to 'System.Collections.ObjectModel.ObservableCollection'
what I am missing here? and how can I remove the duplicate items from the ObservableCollection ?