การพิมพ์เนื้อหาทั้งหมดของอาร์เรย์ใน C #


95

ฉันพยายามพิมพ์เนื้อหาของอาร์เรย์หลังจากเรียกใช้วิธีการบางอย่างที่แก้ไขใน Java ฉันใช้:

System.out.print(Arrays.toString(alg.id));

ฉันจะทำสิ่งนี้ใน c # ได้อย่างไร

คำตอบ:


175

คุณสามารถลองสิ่งนี้:

foreach(var item in yourArray)
{
    Console.WriteLine(item.ToString());
}

นอกจากนี้คุณอาจต้องการลองสิ่งนี้:

yourArray.ToList().ForEach(i => Console.WriteLine(i.ToString()));

แก้ไข:เพื่อให้ได้ผลลัพธ์ในหนึ่งบรรทัด [ตามความคิดเห็นของคุณ]:

 Console.WriteLine("[{0}]", string.Join(", ", yourArray));
 //output style:  [8, 1, 8, 8, 4, 8, 6, 8, 8, 8]

แก้ไข (2019):ตามที่กล่าวไว้ในคำตอบอื่น ๆ ควรใช้Array.ForEach<T>วิธีการดีกว่าและไม่จำเป็นต้องทำตามToListขั้นตอน

Array.ForEach(yourArray, Console.WriteLine);

3
โปรดทราบว่า. ToString ไม่จำเป็นเนื่องจาก WriteLine มีโอเวอร์โหลดต่างๆรวมถึงทางเลือกสำรองที่ใช้ Object
Eren Ersönmez

ฉันใช้ alg.Id ToList () ForEach (Console.WriteLine) ซึ่งทำงานได้ดีขอบคุณ เป็นไปได้ไหมที่จะพิมพ์เช่น: [8, 1, 8, 8, 4, 8, 6, 8, 8, 8]
Padraic Cunningham

@ ErenErsönmezใช่ คุณพูดถูก แต่จะเกิดอะไรขึ้นถ้าไอเท็มนั้นเป็นคลาสแบบกำหนดเองที่มีToStringกลไกของมันเอง
Hossein Narimani Rad

1
ในForEachการใช้แนวทาง: expected.ToList().ForEach(Console.WriteLine);คุณอาจใช้ Method Reference แทน lambda ซึ่งจะสร้างวิธีการใหม่ที่ไม่ระบุตัวตน
Miguel Gamboa

การสร้างรายการโดยToListใช้ForEachวิธีการนี้เป็นวิธีปฏิบัติที่น่าสยดสยองของ IMHO
juharr

60

มีหลายวิธีในการทำคำตอบอื่น ๆ ที่ดีนี่คือทางเลือก:

Console.WriteLine(string.Join("\n", myArrayOfObjects));

ฉันชอบสิ่งนี้เพราะเหมาะกับฉันในการเขียนบันทึก: เช่น myArrayObjects คือ _validExtensions: Write2Log ("เริ่ม blabla ด้วย exenstions:" + string.Join ("-", _validImgExtensions) + "และอื่น ๆ ");
Teo

ฉันชอบสิ่งนี้เช่นกันเพราะมันเข้ากันได้ดีกับการบันทึก และถ้าองค์ประกอบอาร์เรย์เป็นหนึ่งในวัตถุของคุณคุณสามารถแทนที่ToString()และจัดการการจัดรูปแบบได้ที่นั่น var a = new [] { "Admin", "Peon" };_log.LogDebug($"Supplied roles are '{string.Join(", ", a)}'.");
แอรอน

16

วิธีที่ง่ายที่สุดเช่นถ้าคุณมีสตริงอาร์เรย์ที่ประกาศเหมือนสตริงนี้ [] myStringArray = new string [];

Console.WriteLine("Array : ");
Console.WriteLine("[{0}]", string.Join(", ", myStringArray));

10

เนื่องจากมีการหยุดทำงานบางอย่างฉันจึงตัดสินใจทดสอบความเร็วของวิธีต่างๆที่โพสต์ไว้ที่นี่

นี่คือสี่วิธีที่ฉันใช้

static void Print1(string[] toPrint)
{
    foreach(string s in toPrint)
    {
        Console.Write(s);
    }
}

static void Print2(string[] toPrint)
{
    toPrint.ToList().ForEach(Console.Write);
}

static void Print3(string[] toPrint)
{
    Console.WriteLine(string.Join("", toPrint));
}

static void Print4(string[] toPrint)
{
    Array.ForEach(toPrint, Console.Write);
}

ผลลัพธ์มีดังนี้:

Strings per trial: 10000 Number of Trials: 100 Total Time Taken to complete: 00:01:20.5004836 Print1 Average: 484.37ms Print2 Average: 246.29ms Print3 Average: 70.57ms Print4 Average: 233.81ms

ดังนั้น Print3 จึงเร็วที่สุดเนื่องจากมีการเรียกไปยังไฟล์ Console.WriteLineซึ่งดูเหมือนว่าจะเป็นคอขวดหลักสำหรับความเร็วในการพิมพ์อาร์เรย์ Print4 เร็วกว่า Print2 เล็กน้อยและ Print1 ช้าที่สุดในบรรดาทั้งหมด

ฉันคิดว่า Print4 น่าจะเป็น 4 ที่หลากหลายที่สุดที่ฉันทดสอบแม้ว่า Print3 จะเร็วกว่า

หากฉันมีข้อผิดพลาดโปรดแจ้งให้เราทราบ / แก้ไขด้วยตัวคุณเอง!

แก้ไข: ฉันกำลังเพิ่ม IL ที่สร้างขึ้นด้านล่าง

g__Print10_0://Print1
IL_0000:  ldarg.0     
IL_0001:  stloc.0     
IL_0002:  ldc.i4.0    
IL_0003:  stloc.1     
IL_0004:  br.s        IL_0012
IL_0006:  ldloc.0     
IL_0007:  ldloc.1     
IL_0008:  ldelem.ref  
IL_0009:  call        System.Console.Write
IL_000E:  ldloc.1     
IL_000F:  ldc.i4.1    
IL_0010:  add         
IL_0011:  stloc.1     
IL_0012:  ldloc.1     
IL_0013:  ldloc.0     
IL_0014:  ldlen       
IL_0015:  conv.i4     
IL_0016:  blt.s       IL_0006
IL_0018:  ret         

g__Print20_1://Print2
IL_0000:  ldarg.0     
IL_0001:  call        System.Linq.Enumerable.ToList<String>
IL_0006:  ldnull      
IL_0007:  ldftn       System.Console.Write
IL_000D:  newobj      System.Action<System.String>..ctor
IL_0012:  callvirt    System.Collections.Generic.List<System.String>.ForEach
IL_0017:  ret         

g__Print30_2://Print3
IL_0000:  ldstr       ""
IL_0005:  ldarg.0     
IL_0006:  call        System.String.Join
IL_000B:  call        System.Console.WriteLine
IL_0010:  ret         

g__Print40_3://Print4
IL_0000:  ldarg.0     
IL_0001:  ldnull      
IL_0002:  ldftn       System.Console.Write
IL_0008:  newobj      System.Action<System.String>..ctor
IL_000D:  call        System.Array.ForEach<String>
IL_0012:  ret   

8

อีกวิธีหนึ่งกับArray.ForEach<T> Method (T[], Action<T>)วิธีการของArrayคลาส

Array.ForEach(myArray, Console.WriteLine);

ที่ใช้การวนซ้ำเพียงครั้งเดียวเมื่อเทียบกับarray.ToList().ForEach(Console.WriteLine)การทำซ้ำสองครั้งและสร้างอาร์เรย์ที่สองภายในสำหรับList(รันไทม์การวนซ้ำสองครั้งและการใช้หน่วยความจำสองครั้ง)


1
ฉันชอบวิธีของคุณมากที่สุดมันเร็วที่สุดเป็นอันดับสองตามการทดสอบของฉัน แต่มันหลากหลายกว่าวิธีที่เร็วที่สุด (ในความคิดของฉัน)
TJ Wolschon

2

ใน C # คุณสามารถวนลูปผ่านอาร์เรย์ที่พิมพ์แต่ละองค์ประกอบได้ โปรดสังเกตว่า System.Object กำหนดเมธอด ToString () ประเภทใดก็ตามที่มาจาก System.Object () สามารถแทนที่สิ่งนั้นได้

ส่งคืนสตริงที่แสดงถึงวัตถุปัจจุบัน

http://msdn.microsoft.com/en-us/library/system.object.tostring.aspx

ตามค่าเริ่มต้นชื่อชนิดเต็มของวัตถุจะถูกพิมพ์แม้ว่าชนิดในตัวหลายประเภทจะแทนที่ค่าเริ่มต้นนั้นเพื่อพิมพ์ผลลัพธ์ที่มีความหมายมากขึ้น คุณสามารถแทนที่ ToString () ในอ็อบเจ็กต์ของคุณเองเพื่อให้ได้ผลลัพธ์ที่มีความหมาย

foreach (var item in myArray)
{
    Console.WriteLine(item.ToString()); // Assumes a console application
}

หากคุณมีคลาส Foo ของคุณเองคุณสามารถแทนที่ ToString () เช่น:

public class Foo
{
    public override string ToString()
    {
        return "This is a formatted specific for the class Foo.";
    }
}

1

เริ่มจากC # 6.0เมื่อมีการนำ$ - การแก้ไขสตริงมาใช้มีอีกวิธีหนึ่ง:

var array = new[] { "A", "B", "C" };
Console.WriteLine($"{string.Join(", ", array}");

//output
A, B, C

เรียงต่อกันอาจจะเก็บไว้ใช้System.Linq, แปลงstring[]ไปchar[]และพิมพ์เป็นstring

var array = new[] { "A", "B", "C" };
Console.WriteLine($"{new String(array.SelectMany(_ => _).ToArray())}");

//output
ABC

0

ถ้าอยากน่ารักก็เขียนวิธีการขยายที่เขียนIEnumerable<object>ลำดับลงคอนโซล สิ่งนี้จะใช้ได้กับการแจงนับประเภทใดก็ได้เนื่องจากIEnumerable<T>มีความแปรปรวนร่วมกับ T:

using System;
using System.Collections.Generic;

namespace Demo
{
    internal static class Program
    {
        private static void Main(string[] args)
        {
            string[] array  = new []{"One", "Two", "Three", "Four"};
            array.Print();

            Console.WriteLine();

            object[] objArray = new object[] {"One", 2, 3.3, TimeSpan.FromDays(4), '5', 6.6f, 7.7m};
            objArray.Print();
        }
    }

    public static class MyEnumerableExt
    {
        public static void Print(this IEnumerable<object> @this)
        {
            foreach (var obj in @this)
                Console.WriteLine(obj);
        }
    }
}

(ฉันไม่คิดว่าคุณจะใช้สิ่งนี้นอกเหนือจากรหัสทดสอบ)


ฉันใช้เวลาสักพักเพื่อทำความเข้าใจอย่างถ่องแท้ แต่มันมีประโยชน์มากฉันคุ้นเคยกับ Python และใส่คำสั่งพิมพ์เพื่อช่วยในการดีบักดังนั้นสิ่งนี้จึงดีสำหรับฉันขอบคุณ
Padraic Cunningham

0

ฉันยกระดับคำตอบวิธีการขยายโดย Matthew Watson แต่ถ้าคุณกำลังย้าย / เยี่ยมชมที่มาจาก Python คุณอาจพบว่าวิธีการดังกล่าวมีประโยชน์:

class Utils
{
    static void dump<T>(IEnumerable<T> list, string glue="\n")
    {
        Console.WriteLine(string.Join(glue, list.Select(x => x.ToString())));
    }
}

-> สิ่งนี้จะพิมพ์คอลเล็กชันใด ๆ โดยใช้ตัวคั่นที่มีให้ มันค่อนข้าง จำกัด (คอลเลกชันที่ซ้อนกัน?)

สำหรับสคริปต์ (เช่นแอปพลิเคชันคอนโซล C # ซึ่งมีเฉพาะ Program.cs และสิ่งต่างๆส่วนใหญ่เกิดขึ้นในProgram.Main) สิ่งนี้อาจใช้ได้ดี


0

นี่เป็นวิธีที่ง่ายที่สุดที่คุณสามารถพิมพ์ String โดยใช้ array !!!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace arraypracticeforstring
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] arr = new string[3] { "Snehal", "Janki", "Thakkar" };

            foreach (string item in arr)
            {
                Console.WriteLine(item.ToString());
            }
            Console.ReadLine();
        }
    }
}

0

หากเป็นอาร์เรย์ของสตริงคุณสามารถใช้Aggregate

var array = new string[] { "A", "B", "C", "D"};
Console.WriteLine(array.Aggregate((result, next) => $"{result}, {next}")); // A, B, C, D

ด้วยวิธีนี้คุณสามารถย้อนกลับคำสั่งได้โดยการเปลี่ยนลำดับของพารามิเตอร์ดังนี้

Console.WriteLine(array.Aggregate((result, next) => $"{next}, {result}")); // D, C, B, A

0

คุณสามารถใช้สำหรับการวนซ้ำ

    int[] random_numbers = {10, 30, 44, 21, 51, 21, 61, 24, 14}
    int array_length = random_numbers.Length;
    for (int i = 0; i < array_length; i++){
        if(i == array_length - 1){
              Console.Write($"{random_numbers[i]}\n");
        } else{
              Console.Write($"{random_numbers[i]}, ");
         }
     }

-2

หากคุณไม่ต้องการใช้ฟังก์ชัน Array

public class GArray
{
    int[] mainArray;
    int index;
    int i = 0;

    public GArray()
    {
        index = 0;
        mainArray = new int[4];
    }
    public void add(int addValue)
    {

        if (index == mainArray.Length)
        {
            int newSize = index * 2;
            int[] temp = new int[newSize];
            for (int i = 0; i < mainArray.Length; i++)
            {
                temp[i] = mainArray[i];
            }
            mainArray = temp;
        }
        mainArray[index] = addValue;
        index++;

    }
    public void print()
    {
        for (int i = 0; i < index; i++)
        {
            Console.WriteLine(mainArray[i]);
        }
    }
 }
 class Program
{
    static void Main(string[] args)
    {
        GArray myArray = new GArray();
        myArray.add(1);
        myArray.add(2);
        myArray.add(3);
        myArray.add(4);
        myArray.add(5);
        myArray.add(6);
        myArray.print();
        Console.ReadKey();
    }
}
โดยการใช้ไซต์ของเรา หมายความว่าคุณได้อ่านและทำความเข้าใจนโยบายคุกกี้และนโยบายความเป็นส่วนตัวของเราแล้ว
Licensed under cc by-sa 3.0 with attribution required.