如何从混合数据类型数组中仅提取一种数据类型值?

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

我的数组列表中有 4 种不同的数据类型。这些特定于我的应用程序(不是常见的数据类型) 例如,数组 abc 包含 10 个值 Datatype1 - 4 个值, Datatype2 - 2 个值, Datatype3 - 2 个值, 数据类型 4 - 2 个值。 ? 我需要单独提取 Datatype1(即 4 个值)。我该怎么做

您可以使用 OfType<TResult>() extension method 根据特定类型过滤 ArrayList

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
{
}

我假设您使用的是 ArrayList,但此扩展方法适用于任何实现 IEnumerable 的问题。所以即使你使用 object[]List<object>...

也就是说,如果您实际使用的是 ArrayList class then you might want to check out the remarks,因为 Microsoft 不建议您使用 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.