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

问题描述

我的数组列表中有4种不同的数据类型。这些特定于我的应用程序(不是常见的数据类型) 假设阵列abc包含10个值, 数据类型1-4个值, 数据类型2-2个值, 数据类型3-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,那么您可能要签出remarks,因为Microsoft不建议您使用该类。

我们不建议您将ArrayList类用于新开发。相反,我们建议您使用通用的List<T>类。 ArrayList类旨在容纳对象的异构集合。但是,它并不总是提供最佳性能。相反,我们建议以下内容:

对于异构对象集合,请使用List<Object>(在C#中)或List(Of Object)(在Visual Basic中)类型。

对于同类对象,请使用List<T>类。 有关这些类的相对性能的讨论,请参见List<T>参考主题中的性能注意事项。有关使用通用而非非通用集合类型的一般信息,请参阅GitHub上不应该使用非通用集合。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...