Devdit
 

ค้นหา string ใน array C# ด้วย Array.FindAll

1.1K

ค้นหา string ใน array C# ด้วย Array.FindAll บทความนี้สอนเขียนภาษา C# สำหรับค้นหา string หรือข้อความจากตัวแปรชนิด array โดยใช้คำสั่ง Array.FindAll โดย return ค่าเป็นจำนวนข้อมูลที่พบ สามารถเขียนโปรแกรมได้ดังนี้

 

ตัวอย่าง ค้นหา string ใน array C# ด้วย Array.FindAll

using System;

public class HelloWorld
{
    public static void Main(string[] args) {
        string[] colors = { "red", "green", "blue" };
        var find = "blue";
        var results = Array.FindAll(colors, s => s.Equals( find ));
        if( results.Length > 0 ) {
            Console.Write("พบ string blue ใน array colors");
        } else {
            Console.Write("ไม่พบ string blue ใน array colors");
        }
    }
}

ผลลัพธ์

พบ string blue ใน array colors

คำอธิบาย

ค้นหา string ใน array C# ด้วย Array.FindAll จากตัวอย่างใช่คำสั่ง Array.FindAll(colors, s => s.Equals( find )) หมายความว่าให้ค้นหา string ของตัวแปร find ในตัวแปร array ชื่อ colors และเก็บผลลัพธ์การค้นหาไว้ที่ตัวแปร result จากนั้นใช้คำสั่ง if( results.Length > 0 ) เช็คว่าหากตัวแปร result มีจำนวนข้อมูลที่พบมากกว่า 0 คือมีข้อมูลให้ทำงานในคำสั่ง if กรณีไม่พบให้ทำงานในคำสั่ง else

เขียน 1 ปีที่แล้ว
ชอบ
ลิ้งก์
แชร์
Devdit มีช่อง YouTube แล้ว
เราสร้างวิดีโอเกี่ยวกับเทคโนโลยี ทำตามง่ายๆ