在C#中,可以使用List
假設有一個復雜對象Person,包含姓名、年齡和性別屬性:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public string Gender { get; set; }
}
現在我們可以創建一個List
List<Person> people = new List<Person>();
// 添加Person對象到List中
Person person1 = new Person { Name = "Alice", Age = 30, Gender = "Female" };
people.Add(person1);
Person person2 = new Person { Name = "Bob", Age = 25, Gender = "Male" };
people.Add(person2);
// 遍歷List中的Person對象
foreach (Person person in people)
{
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}, Gender: {person.Gender}");
}
// 查找特定條件的Person對象
Person foundPerson = people.Find(p => p.Name == "Alice");
if (foundPerson != null)
{
Console.WriteLine($"Found: Name: {foundPerson.Name}, Age: {foundPerson.Age}, Gender: {foundPerson.Gender}");
}
// 對List中的Person對象進行排序
people.Sort((p1, p2) => p1.Age.CompareTo(p2.Age));
// 刪除List中的某個Person對象
people.Remove(person2);
通過以上示例,我們可以看到如何使用List