This is a post to get the specific type of items from a mixed list of items. I have tried couple of solutions for the problem but it looks like there’s more elegant solution than my solution.
There will be a list of objects from which we have to extract only integers from it.
We’ve to implement the solution in
GetOnlyInts() method so as to return only integers from it.
A Draft thought
Once you are given that problem, we tend to loop over the content and try to find out the type of each item and store that in another list and return that back.
But as we think through, the
listOfObjects is a List. So, there’s no need of the for loop and add it to result variable. We’ll fine tune here using LINQ.
Ignore the method signature.
This is a good solution and observe how we eliminated the failed cases in the where clause filter.
The ‘OfType’ extension method only the specific type of item that is requested on.
Let’s examine the source code of OfType extension method to see what it has.
OfType() source code
As you can see from the above source code of
OfType method, it has the same old foreach statement on the
IEnumerable. But it yield returns the values.
If the type of the object is
TResult, then the value is returned by casting it to
Subscribe to Code Rethinked
Get the latest posts delivered right to your inbox