首页 > 解决方案 > 如何在 C# 中遍历和读取对象的 ArrayLists 的 ArrayList 中的值?

问题描述

我想遍历包含不同对象类型的 ArrayList 的 ArrayList 并将数据写入控制台。

我尝试使用 IEnumerable 和 foreach 循环。

//-------------------- Custom class Point --------------------
class Point
{
    public double X { get; set; }
    public double Y { get; set; }
    public double Z { get; set; }
    public Point(double x, double y, double z) { this.X = x; this.Y = y; this.Z = z; }
}
//-------------------- Main program --------------------
class Program
{
    static void Main(string[] args)
    {
        //ArrayList of different objects
        ArrayList arrlist = new ArrayList{
            new ArrayList { 1, "one" ,new Point(1.0,1.0,1.0)},
            new ArrayList { "two", 2,new Point(2.0,2.0,2.0) },
            new ArrayList { new Point(3.0,3.0,3.0), "three",3}
        };
        readData(arrlist);
        Console.ReadLine();
    }
    //-------------------- readData() function definition --------------------
    public static void readData(ArrayList arlst)
    {
        foreach (object obj in arlst)
        {
            foreach (object item in (IEnumerable)obj)
            {
                Console.WriteLine($"... {(IEnumerable)item.ToString()} ...");
            }
        }
    }
}

我希望按照输入的方式在 ArrayList 中写入每个项目的实际值。

编辑:格式化

标签: c#objectarraylistcollectionsiteration

解决方案


您可以将其用作 arraylist 以在 arraylists 上循环,例如,请参阅注释:

public static void readData(ArrayList arlst)
{

    foreach (object l in arlst)
    {
        // try to convert it to arrayList to keep 
        var data = l as ArrayList;safe!
        if (data != null)
           // it is an arrayList, loop on it an print values
           foreach (object item in data)
               Console.WriteLine($"... {item.ToString()} ...");
        else
           // print the value if it is not an array list
           Console.WriteLine($"... {item.ToString()} ...");
    }
}

推荐阅读