假设我们有一个包含 Student 对象的 List,每个 Student 对象都有 Id、Name 和 Age 属性。我们想查询所有学生的名字。

使用 LINQ 语句可以轻松地完成这个任务:

List<Student> students = new List<Student>
{
    new Student { Id = 1, Name = 'Alice', Age = 20 },
    new Student { Id = 2, Name = 'Bob', Age = 22 },
    new Student { Id = 3, Name = 'Charlie', Age = 21 }
};

var names = from s in students
            select s.Name;

foreach (var name in names)
{
    Console.WriteLine(name);
}

输出:

Alice
Bob
Charlie

这里我们使用了 select 子句来选择 Student 对象中的 Name 属性。在 foreach 循环中,我们遍历所有名字并将它们输出到控制台。

C# 使用 LINQ 查询 List 中的字段 - 获取所有学生姓名

原文地址: https://www.cveoy.top/t/topic/mvvm 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录