在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