c#从liststudent中取出name为a的那个元素怎么写
假设Student类具有一个Name属性,可以通过以下方式从List
using System;
using System.Collections.Generic;
public class Program
{
public static void Main(string[] args)
{
List<Student> students = new List<Student>()
{
new Student() { Name = "Alice", Age = 20 },
new Student() { Name = "Bob", Age = 22 },
new Student() { Name = "Charlie", Age = 21 }
};
Student studentWithNameA = students.Find(student => student.Name == "a");
if (studentWithNameA != null)
{
Console.WriteLine("Found student with name 'a': " + studentWithNameA.Name);
}
else
{
Console.WriteLine("No student found with name 'a'");
}
}
}
public class Student
{
public string Name { get; set; }
public int Age { get; set; }
}
在上述代码中,我们使用List<T>.Find方法来查找符合条件的第一个元素。在这个例子中,我们使用了一个lambda表达式student => student.Name == "a"作为参数,表示查找具有Name属性为"a"的Student对象。如果找到了匹配的元素,将其赋值给studentWithNameA变量;否则,将其赋值为null。最后,我们根据studentWithNameA是否为null来判断是否找到了符合条件的元素
原文地址: https://www.cveoy.top/t/topic/iH79 著作权归作者所有。请勿转载和采集!