windows C#-在查询中返回元素属性的子集

当下列两个条件都满足时,可在查询表达式中使用匿名类型:

  • 只想返回每个源元素的某些属性。
  • 无需在执行查询的方法的范围之外存储查询结果。

如果只想从每个源元素中返回一个属性或字段,则只需在 select 子句中使用点运算符。 例如,若要只返回每个 student 的 ID,可以按如下方式编写 select 子句:

复制代码
select student.ID;
示例

下面的示例演示如何使用匿名类型只返回每个源元素的符合指定条件的属性子集。

复制代码
private static void QueryByScore()
{
    // Create the query. var is required because
    // the query produces a sequence of anonymous types.
    var queryHighScores =
        from student in students
        where student.ExamScores[0] > 95
        select new { student.FirstName, student.LastName };

    // Execute the query.
    foreach (var obj in queryHighScores)
    {
        // The anonymous type's properties were not named. Therefore
        // they have the same names as the Student properties.
        Console.WriteLine(obj.FirstName + ", " + obj.LastName);
    }
}
/* Output:
Adams, Terry
Fakhouri, Fadi
Garcia, Cesar
Omelchenko, Svetlana
Zabokritski, Eugene
*/

请注意,如果未指定名称,匿名类型会使用源元素的名称作为其属性名称。 若要为匿名类型中的属性指定新名称,请按如下方式编写 select 语句:

复制代码
select new { First = student.FirstName, Last = student.LastName };

如果在上一个示例中这样做,则 Console.WriteLine 语句也必须更改:

复制代码
Console.WriteLine(student.First + " " + student.Last);
编译代码

要运行此代码,请使用 System.Linq 的 using 指令将该类复制并粘贴到 C# 控制台应用程序中。

相关推荐
weixin_408099672 分钟前
跨境电商OCR:3秒识别多语言商品标签
开发语言·图像处理·人工智能·后端·ocr·api·文字识别ocr
小樱花的樱花3 分钟前
C++引用:高效编程的技巧
开发语言·数据结构·c++·算法
南境十里·墨染春水4 分钟前
C++笔记 继承中重载规则 公有私有继承的区别(面向对象)
开发语言·c++·笔记
遇见你...4 分钟前
B03 SpringMVC拦截器
java·开发语言
沉鱼.445 分钟前
进制转换题
开发语言·c++·算法
淼淼7636 分钟前
QT仪表盘
开发语言·qt
wjcroom6 分钟前
融释涡旋理论-对狭义相对论和洛伦兹变换的兼容
开发语言·前端
大明者省6 分钟前
Python 程序在 Ubuntu 系统的完整部署流程
开发语言·python·ubuntu
咸甜适中6 分钟前
rust序列化和反序列化(json、yaml、toml)详解
开发语言·rust·json
智算菩萨7 分钟前
【Tkinter】14 事件处理机制深度解析:从基础绑定到高级传播,构建交互式绘图笔记应用
开发语言·笔记·python·microsoft·ui·ai编程·tkinter