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# 控制台应用程序中。

相关推荐
helloworddm38 分钟前
Orleans Grain Directory 系统综合分析文档
c#·1024程序员节
「QT(C++)开发工程师」42 分钟前
嵌入式Lua脚本编程核心概念
开发语言·lua
_extraordinary_44 分钟前
Java Spring事务,事务的传播机制
java·开发语言·spring
golang学习记2 小时前
Go slog 日志打印最佳实践指南
开发语言·后端·golang
新手村领路人2 小时前
python opencv gpu加速 cmake msvc cuda编译问题和设置
开发语言·python·opencv
dengzhenyue3 小时前
C# 初级编程
开发语言·c#
jf加菲猫3 小时前
条款20:对于类似std::shared_ptr但有可能空悬的指针使用std::weak_ptr
开发语言·c++
jf加菲猫4 小时前
条款21:优先选用std::make_unique、std::make_shared,而非直接new
开发语言·c++
消失的旧时光-19434 小时前
Kotlin 高阶函数在回调设计中的最佳实践
android·开发语言·kotlin
LucianaiB4 小时前
掌握 Rust:从内存安全到高性能服务的完整技术图谱
开发语言·安全·rust