Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

เมธอด Enumerable.Repeat ใน C#

เมธอด Enumerable.Repeat(T element, int count) สร้างลำดับที่มีองค์ประกอบ element ซ้ำ count ครั้ง อยู่ในเนมสเปซ System.Linq

ตัวอย่าง: สร้างลำดับเลข 10 จำนวน 5 ครั้ง

using System;
using System.Linq;

class Demo
{
    static void Main()
    {
        var val = Enumerable.Repeat(10, 5);
        foreach (int res in val) Console.WriteLine(res);
    }
}

ผลลัพธ์

10
10
10
10
10

ประโยชน์: สร้างข้อมูลทดสอบ, เริ่มต้นอาร์เรย์/ลิสต์ด้วยค่าเดิม, หรือใช้ร่วมกับ LINQ อื่นๆ เช่น Zip, Concat