How can I extract only one datatype values from a mixed datatype array?

68 Views Asked by At

I am having 4 different datatypes in my array list. These are specific to my application(not common data types) Say for example Array abc has contain 10 values with Datatype1 - 4 values, Datatype2 - 2 values, Datatype3 - 2 values, Datatype4 - 2 values. ? I need to extract Datatype1 alone(i.e 4 values). How can I do that

1

There are 1 best solutions below

3
On BEST ANSWER

You can use the OfType<TResult>() extension method to filter your ArrayList based on a specific type.

using System;
using System.Collections;
using System.Linq;
                    
public class Program
{
    public static void Main()
    {
        var arrayList = new ArrayList();
        arrayList.Add(new Type1());
        arrayList.Add(new Type2());
        arrayList.Add(new Type3());
        arrayList.Add(new Type1());
        arrayList.Add(new Type2());
        arrayList.Add(new Type3());
        arrayList.Add(new Type1());
        arrayList.Add(new Type2());
        arrayList.Add(new Type3());
        arrayList.Add(new Type1());
        arrayList.Add(new Type2());
        arrayList.Add(new Type3());
        arrayList.Add(new Type1());
        arrayList.Add(new Type2());
        arrayList.Add(new Type3());
        arrayList.Add(new Type1());
        arrayList.Add(new Type2());
        arrayList.Add(new Type3());
        
        foreach (Type1 t in arrayList.OfType<Type1>())
        {
            Console.WriteLine(t.ToString());
        }
    }
}

public class Type1
{
    
}

public class Type2
{
}

public class Type3
{
}

I'm assuming based on the language in your question that you're using an ArrayList, but this extension method will work on anything that implements IEnumerable. So this will work even if you're using an object[] or a List<object>...

That said, if you're actually using the ArrayList class then you might want to check out the remarks as Microsoft does not recommend that you use that class.

We don't recommend that you use the ArrayList class for new development. Instead, we recommend that you use the generic List<T> class. The ArrayList class is designed to hold heterogeneous collections of objects. However, it does not always offer the best performance. Instead, we recommend the following:

For a heterogeneous collection of objects, use the List<Object> (in C#) or List(Of Object) (in Visual Basic) type.

For a homogeneous collection of objects, use the List<T> class. See Performance Considerations in the List<T> reference topic for a discussion of the relative performance of these classes. See Non-generic collections shouldn't be used on GitHub for general information on the use of generic instead of non-generic collection types.