I have a class that is derived from List. I am not able to use intersect() on instances of my class. Why?
What I have is:
class myList : List<int>
{ ... }
What I try to do is
myList list1 = new some initialization...
myList list2 = new some initialization...
myList list3 = list1.Intersect(list2);
This doesn't work. Compiler complains about something like "Error 1 Typ "System.Collections.Generic.IEnumerable" cannot be converted implicitly into "myList"."
I do not understand what type of type confusion is going on here :( I already tried some casts in my Intersect-example but it did not work.
Can anyone please explain me what's the problem here, and what I made wrong?
Thanks!
The Intersect
extension method doesn't try to return a collection of the same kind as the inputs (e.g. a List<int>
). It just returns a sequence implementing IEnumerable<T>
for an appropriate T
. So in your case you could use:
myList list1 = new some initialization...
myList list2 = new some initialization...
IEnumerable<int> list3 = list1.Intersect(list2);
If you want to create a myList
with that content, you'll need to do so with something like:
myList list4 = new myList();
list4.AddRange(list3);
(Or if your class provides a constructor accepting an IEnumerable<int>
parameter, that would work too.)
See more on this question at Stackoverflow