Nuts
Nuts

Reputation: 2813

Cast IEnumerable into ObservableCollection

How to efficiently cast IEnumerable into ObservableCollection WITHOUT creating a new ObservableCollection in a WPF application?

All examples I have seen require creating a new ObservableCollection but I don't want that.

Upvotes: 1

Views: 674

Answers (3)

supercat
supercat

Reputation: 81179

Given an IEnumerable of some unknown arbitrary type, there is no way to know when something happens that could change the returned sequence. If one wishes to receive notifications when the sequence changes, and one doesn't recognize a particular implementation of IEnumerable or IEnumerator, the best one can reasonably hope to do is periodically enumerate the sequence to an array, compare the result with that of the previous enumeration, and raise a notification event when something is found to have changed. Such an approach may be workable if the collection is small and one's timeliness requirements aren't too strict; one should probably, however, limit the the amount of data one is willing to examine and the fraction of available of time that will be spent examining it. Otherwise trying to watch a large sequence may gobble up huge amounts of memory, CPU time, or both.

Upvotes: 0

Andrei
Andrei

Reputation: 44600

"Casting" in fact is creating new collection, if object cannot be interpreted implicitly. There is no way to cast IEnumerable to ObservableCollection by out-of-the-box solution. But you can create your own extension method. And Yes you have to create new ObservableCollection.

public static class EnumerableExtension
{       
   public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> source)
   {
         ObservableCollection<T> collection = new ObservableCollection<T>();
         foreach (T item in source) collection.Add(item);
         return collection;
   }
}

Upvotes: 3

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391406

If the underlying object is not ObservableCollection, nor any of its descendants, then simply can't do that.

"Casting" an object does one of two things:

  1. A cast, reinterpret the reference to a different type, this only works if the underlying type is that different type, or implement the interface if you're casting to interface.
  2. A conversion, like int a = (int)dbl;

In your case neither will work as there is no such conversion available, and reinterpretation only works if the underlying type is a ObservableCollection, so you're left with what you don't want to do:

You need to create a new ObservableCollection

Upvotes: 6

Related Questions