Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a Generic IList<T> to IList?

Tags:

c#

wpf

I want to create a ListCollectionView with a generic IList<T> but the constructor gets a non-generic IList. How can I convert my list from IList<T> to IList?

if there is another way to create a ListCollectionView with a generic IList<T> I would like to hear it :)

like image 359
Natalie Avatar asked Apr 14 '19 12:04

Natalie


2 Answers

Annoyingly, IList<T> is one of those interfaces which doesn't implement its non-generic counterpart IList.

If you can find a way to pass a List<T> rather than an IList<T> (or some other type which implements IList as well as IList<T>, such as ObservableCollection<T>), that's going to be easiest. This might mean changing your application so that you pass a List<T> or something else around rather than an IList<T>.

Otherwise, you might have to create a new List<T> using the elements in the IList<T>, and pass that (i.e. myList.ToList()). Note that this means that you've created a copy of your list, and so changes to the original won't be reflected in the copy. In particular, ListCollectionView checks to see whether the source collection implements INotifyCollectionChanged, and subscribes to collection changed events if so: this obviously won't work if you create a copy of your list.

like image 59
canton7 Avatar answered Nov 09 '22 22:11

canton7


List<T> implements IList (IList<T> does not). Create a List<T> from your IList<T> and pass that to the ListCollectionView constructor:

ListCollectionView lcv = new ListCollectionView(new List<YourType>(yourIList));
like image 45
ProgramFOX Avatar answered Nov 10 '22 00:11

ProgramFOX