簡體   English   中英

使用鋸齒狀的 arrays 打印部門名稱及其自己的員工及其年齡

[英]print Section name and it's own employees with their ages using jagged arrays

我正在嘗試使用鋸齒狀的 arrays 來打印部門名稱及其員工姓名和年齡我試過這樣:

string[] sections= new string[50];
            sections[0] = "It";
            sections[1] = "Hr";
            string[][,] employeeTree = new string[6][,];
            
            employeeTree [0] = new string[,] { {"mark","20"},{ "mike", "30" },{ "michel", "3" },{ "joerge", "40" }};

我的問題是迭代員工 arrays 來打印它們,我該怎么做? 如果有例子會更好

您有一個用於employeeTree 的二維數組結構。 因此,直接的方法是在二維數組上迭代兩次以訪問元素。

最簡單的方法如下:

foreach(var emp in employeeTree.Where(x => x != null) )
                foreach(var object1 in emp)
                    Console.WriteLine(object1.ToString());

這將打印以下 output:

標記

20

麥克風

30

米歇爾

3

豪爾赫

40

您可以對此進行格式化以將它們打印在一行中,如下所示:

foreach (var emp in employeeTree.Where(x => x != null))
                for (int i = 0; i < emp.GetLength(0); i++)
                {
                    Console.WriteLine(emp[i,0] + emp[i,1]);
                }
        foreach(string[,] employee in employeeTree.Where(x => x != null)) {
            int max = employee.GetLength(0);
            for (int i = 0; i < max; i++) {
                Console.WriteLine($"{employee[i, 0]}, {employee[i, 1]}");
            }
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM