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.
List<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
public static IEnumerable<int> GetOnlyInts(List<object> listOfObjects) { var result = new List<int>(); foreach(var item in listOfObjects) { if (item is int) result.Add((int)item); } return result; }
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.
Solution 2
return listOfObjects.Select(a => { return new { success = a is int, val = a }; }) .Where(a => a.success) //filter only successful integers .Select(v => (int)v.val).ToList(); //return to a list of integers });
This is a good solution and observe how we eliminated the failed cases with the where
filter.
Best/Short solution
public static IEnumerable<int> GetOnlyInts(List<object> listOfObjects) { return listOfObjects.OfType<int>(); }
The OfType
extension method only filters specific data type of item.
In the above code, we asked for int
type of data in the list of items and we should see a new list with only integer type of data.
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
public static IEnumerable<TResult> OfType<TResult>(this IEnumerable source) { if (source == null) throw Error.ArgumentNull("source"); return OfTypeIterator<TResult>(source); } static IEnumerable<TResult> OfTypeIterator<TResult>(IEnumerable source) { foreach (object obj in source) { if (obj is TResult) yield return (TResult)obj; } }
As you can see from the above source code, it has the same old foreach statement on the IEnumerable
. But, its yield returns values by casting to the generic type.
Karthik is a passionate Full Stack developer working primarily on .NET Core, microservices, distributed systems, VUE and JavaScript. He also loves NBA basketball so you might find some NBA examples in his posts and he owns this blog.