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.
Problem
There will be a list of objects from which we have to extract only integers from it.
Ex:1
2List<object> listOfObjects = new List<object>{ "tada", 10, "123", 22.0 "sttring", 1};
IEnumerable<int> result = GetOnlyInts(listOfObjects); //the result should b 10, 1
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.
Solution 1
1 | public static IEnumerable<int> GetOnlyInts(List<object> listOfObjects) |
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.
Solution 2
1 | return listOfObjects.Select(a => { |
This is a good solution and observe how we eliminated the failed cases in the where clause filter.
Best/Short solution
1 | public static IEnumerable<int> GetOnlyInts(List<object> listOfObjects) |
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
Source code link to OfType extension method
1 | public static IEnumerable<TResult> OfType<TResult>(this IEnumerable source) { |
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 TResult
.