I know I can create a List<T> from IEnumerable<T> by doing myEnumerableCollection.ToList(), but how could I implement the same thing for an ObservableCollection<T> ?
Asked
Active
Viewed 3,508 times
2
Jake Berger
- 5,237
- 1
- 28
- 22
MaesterZ
- 72
- 1
- 9
-
dup? http://stackoverflow.com/questions/3559821/how-to-convert-ienumerable-to-observablecollection – kenny Jun 19 '12 at 15:11
-
Why do you guys expect upvotes from him since you downvote the question? – Piotr Justyna Jun 19 '12 at 15:17
-
that's not a "cast", you're actually creating a new `List
` – Jake Berger Jun 19 '12 at 15:31
4 Answers
9
What you're looking for is extension methods.
You can extend the IEnumerable<T> type like this:
namespace myNameSpace
{
public static class LinqExtensions
{
public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> _LinqResult)
{
return new ObservableCollection<T>(_LinqResult);
}
}
}
Don't forget to add the using directive in classes you want to use this in (i.e: using myNameSpace;)
Louis Kottmann
- 16,268
- 4
- 64
- 88
5
Why would you need to cast it? That's syntactic sugar for common operations.
var observableCollection = new ObservableCollection<object>(regularCollection);
Trevor Elliott
- 11,292
- 11
- 63
- 102
1
this works for me:
List<string> ll = new List<string> { "a", "b","c" };
ObservableCollection<string> oc = new ObservableCollection<string>(ll);
Yoav
- 3,326
- 3
- 32
- 73
0
You have to create new ObservableCollection instance populated with your collection (IEnumerable).
Piotr Justyna
- 4,888
- 3
- 25
- 40