Get Only Specific Types From List In C#

This is a LINQ puzzle to get only specific integers from a list of objects in the list.

This is a post to get the specific type of items from a mixed list of items. I have tried a couple of solutions to the problem but it looks like there's a more elegant solution than my solution.

Problem statement

There will be a list of objects from which we have to extract only integers.
  1. List<object> listOfObjects = new List<object>{ "tada", 10, "123", 22.0 "sttring", 1};  
  2. IEnumerable<int> result = GetOnlyInts(listOfObjects); //the result should b 10, 1  
We have 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)  
  2. {  
  3.     var result = new List<int>();  
  4.     foreach(var item in listOfObjects)  
  5.     {  
  6.         if (item is int)  
  7.           result.Add((int)item);  
  8.     }  
  9.     return result;  
  10. }  
But as we think it through, the listOfObjects is a List. So, there's no need of the for loop and adding it to the result variable. We'll fine tune it here using LINQ.

Ignore the method signature.

Solution 2
  1. return listOfObjects.Select(a => {  
  2.         return new { success = a is int, val = a };  
  3.       })  
  4.       .Where(a => a.success) //filter only successful integers  
  5.       .Select(v => (int)v.val).ToList(); //return to a list of integers  
  6. });  
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)  
  2. {  
  3.     return listOfObjects.OfType<int>();  
  4. }  
The 'OfType' extension method returns only the specific type of item that is requested.

Let's examine the source code of the OfType extension method to see what it has.

OfType() source code

Source code link to the OfType extension method
  1. public static IEnumerable<TResult> OfType<TResult>(this IEnumerable source) {  
  2.     if (source == nullthrow Error.ArgumentNull("source");  
  3.     return OfTypeIterator<TResult>(source);  
  4. }  
  6. static IEnumerable<TResult> OfTypeIterator<TResult>(IEnumerable source) {  
  7.     foreach (object obj in source) {  
  8.         if (obj is TResult) yield return (TResult)obj;  
  9.     }  
  10. }  
As you can see from the above source code of the OfType method, it has the same old foreach statement on the IEnumerable. But its yield returns the values.

If the type of the object is TResult, then the value is returned by casting it to TResult.