Let’s say I have instance of MyCollection class called Foo1. MyCollection is basically a collection of MyClass. Not sure how can I do something like below with or without a cast?
MyCollection Foo2 = Foo1.Where( r => r.LastName == “SomeName”)
NOTE: MyCollection & MyClass are something from a 3rd party library. I probably can create extension method on it but hoping to have some easy way of doing it.
If you want to have a new instance of
MyCollectionholding only those elements that meet the criteria, you can create aWheremethod on your class.Or, you can rely on the linq extension method on
IEnumerable<T>(assuming your class implementsIEnumerable<MyClass>), and use whatever method you would normally use for populating aMyCollectionfrom a sequence ofMyClassobjects.EDIT
Example of linq extension method approach:
MyCollectionimplementsIEnumerable<MyClass>MyCollectionhas a constructor that accepts anIEnumerable<MyClass>#using System.Linq;MyCollection Foo2 = new MyCollection(Foo1.Where( r => r.LastName == “SomeName”));EDIT EDIT
I see now that MyClass and MyCollection are third-party types. I had assumed from the “my” bit that you were designing them yourself.
The
MyCollectiontype almost certainly implementsIEnumerable<MyClass>— if it doesn’t, it may implement the non-genericIEnumerable. In that case, you can use theCast<T>extension method. If it implements neither interface, the third-party library is somewhat lacking.