【问题标题】:How can I extract only one datatype values from a mixed datatype array?如何从混合数据类型数组中仅提取一个数据类型值?
【发布时间】:2021-01-31 01:47:41
【问题描述】:

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

【问题讨论】:

    标签: c# arrays multidimensional-array element custom-data-type


    【解决方案1】:

    您可以使用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&lt;object&gt;,这也可以工作...

    也就是说,如果您实际使用的是 ArrayList class,那么您可能需要查看 remarks,因为 Microsoft 不建议您使用该类。

    我们不建议您将 ArrayList 类用于新开发。相反,我们建议您使用通用的List&lt;T&gt; 类。 ArrayList 类旨在保存异构的对象集合。但是,它并不总是提供最佳性能。相反,我们建议如下:

    对于对象的异构集合,请使用 List&lt;Object&gt;(在 C# 中)或 List(Of Object)(在 Visual Basic 中)类型。

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

    【讨论】:

    • 谢谢约书亚。不,我使用的是 Array[] 而不是 arraylist。但是,这对我有用。但是我提出这个问题的意图是无论如何都要在不循环每个元素的情况下做到这一点?因为循环元素消耗更多时间
    • 我们可以使用任何方法如array.cast().Any()
    • 如果数组中的任何对象无法转换为datatype1Cast&lt;datatype1&gt;() 将抛出InvalidCastException。而Any() 将只返回truefalse 指示IEnumerable 中是否有任何项目......它不会让您在array 中获得datatype1 类型的所有项目,这就是你的问题似乎是。恐怕如果您拥有的是Arrayobject[],那么没有任何方法可以在不迭代整个数组的情况下获取datatype1 类型的所有元素。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-11
    • 2021-01-19
    • 2015-07-24
    • 1970-01-01
    • 2022-08-23
    • 2012-03-11
    • 2018-08-27
    相关资源
    最近更新 更多