C# – 透過泛型方法搜尋Array

Array 及 Object

public class Person{
   string name = "";
   int age = 0;
   string gender = "";
   
   public Person(string name, int age, string gender){
     this.name = name;
     this.age = age;
     this.gender = gender;
   }
}
Person p1 = new Person("elvis", 18, "M");
Person p2 = new Person("rex", 31, "M");
Person p3 = new Person("noah", 30, "M");
Person p4 = new Person("jason", 29, "M");
Person p5 = new Person("jennifer", 47, "F");


//將p1-p5 放進 perons array
Person[] persons = new Person[5];
persons[0] = p1;
persons[1] = p2;
persons[2] = p3;
persons[3] = p4;
persons[4] = p5;

實際用法 (Array.Find)

string find_name = "jason";
int find_age = 20;
string find_gender = "M";

/* 注意 */
/* 只會返回第1個結果 */

//搜尋 name
Person p = Array.Find(persons, p => c.name == find_name);

//搜尋 name 及 age
Person p2 = Array.Find(persons, p => c.name == find_name && p.age > 20); 

//搜尋 gender
Person p3 = Array.Find(persons, p => p.gender == find_gender);

實際用法 (Array.FindAll)

string find_name = "jason";
int find_age = 20;
string find_gender = "M";

//這裡是回傳一個 Person的Array
Person[] p = Array.FindAll(persons, p => p.gender == find_gender);

if(p.Length > 0){
  foreach(Person current_p in p){
    Console.WriteLine($"Person: {current_p.name} Age: {current_p.age} Gender: {current_p.gender}");
  }
}
else{
  //沒有符合的結果
}

開始在上面輸入您的搜索詞,然後按回車進行搜索。按ESC取消。

返回頂部