C#

Get only specific types from List in C#

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.

Disqus Comments Loading...
Share
Published by
Karthik Chintala

Recent Posts

2 Good Tools To Test gRPC Server Applications

In this post, we’ll see how to test gRPC Server applications using different clients. And… Read More

2 years ago

Exploring gRPC project in ASP.NET Core

In this post, we'll create a new gRPC project in ASP.NET Core and see what's… Read More

2 years ago

Run dotnet core projects without opening visual studio

In this blog post, we’ll see how to run dotnet core projects without opening visual… Read More

2 years ago

Programmatically evaluating policies in ASP.NET Core

Programmatically evaluating policies is useful when we want to provide access or hide some data… Read More

2 years ago

Multiple authorization handlers for the same requirement in ASP.NET Core

We saw how we could set up policy-based authorization in our previous article. In this… Read More

2 years ago

Policy-Based Authorization in ASP.NET Core

What is policy-based authorization and how to set up policy-based authorization with handlers and policies… Read More

2 years ago

This website uses cookies.