c# - 如何在 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 中写入每个项目的实际值。
编辑:格式化
解决方案
您可以将其用作 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()} ...");
}
}
推荐阅读
- python - 在python中只计算一次列表中的元素而不重复
- linux - Linux:加载共享库时出错:libQtSvg.so.4:无法打开共享对象文件:没有这样的文件或目录
- php - 如何选择符合 now() 日期条件的人的年龄
- ios - CASpringAnimation的initialVelocity的单位是什么?
- google-chrome-extension - 在 Chrome 扩展程序中显示 Adsense 广告
- pygame - Pygame“模块”对象没有属性“事件”
- javascript - 循环访问 JSON 响应对象
- azure - 使用 Azure 数据工厂将带有元数据的 Azure Blob 从一个存储帐户复制到另一个存储帐户
- android - Travis CI 密钥问题
- r - R中的部分字符串匹配并修剪字符