LINQ 查询表达式

来源:互联网 发布:中国保险网络大学考试 编辑:程序博客网 时间:2024/05/20 08:27

       点击打开链接

       语言集成查询 (LINQ) 是一组技术的名称,这些技术建立在将查询功能直接集成到 C# 语言(以及 Visual Basic 和可能的任何其他 .NET 语言)的基础上。借助于 LINQ,查询现在已是高级语言构造,就如同类、方法、事件等等。

       对于编写查询的开发人员来说,LINQ 最明显的“语言集成”部分是查询表达式。查询表达式是使用 C# 3.0 中引入的声明性查询语法编写的。通过使用查询语法,您甚至可以使用最少的代码对数据源执行复杂的筛选、排序和分组操作您使用相同的基本查询表达式模式来查询和转换 SQL 数据库、ADO.NET 数据集、XML 文档和流以及 .NET 集合中的数据。

下面的示例演示了完整的查询操作。完整操作包括创建数据源、定义查询表达式,以及在 foreach 语句中执行查询。

    class Program
    {
       
static voidMain(string[] args)
        {
            // Specify the data source.
           
int[] scores = new int[] { 97, 92, 81, 60 };
            // Define the query expression.
           
IEnumerable<int> scoreQuery = from score in scores
                                                                  
where score > 80
                                                                  
select score;
            // Execute the query.
            foreach
(int i in scoreQuery)
            {
               
Console.Write(i + " ");
            }  
        }
    }

查询表达式概述

1、在您循环访问foreach语句中的查询变量之前,不会执行查询。

2、作为编写 LINQ 查询的一项规则,建议尽量使用查询语法,只在必需的情况下才使用方法语法这两种不同形式在语义或性能上没有区别。查询表达式通常比用方法语法编写的等效表达式更易读

3、一些查询操作,如 Count<TSource> 或 Max,没有等效的查询表达式子句,因此必须表示为方法调用。方法语法可以通过多种方式与查询语法组合。

4、查询表达式可以编译为表达式树或委托,具体取决于查询所应用到的类型。 IEnumerable<T> 查询编译为委托。 IQueryable 和IQueryable<T> 查询编译为表达式树。

5、查询表达式中的变量都是强类型的,但许多情况下您不需要显式提供类型,因为编译器可以推断类型。

6、查询表达式可用于查询和转换来自任意支持 LINQ 的数据源中的数据。例如,单个查询可以从 SQL 数据库检索数据,并生成XML 流作为输出。

如何:在查询表达式中处理异常

     在某些情况下,对在查询内引发的异常的最佳响应可能是立即停止执行查询下面的示例演示如何处理可能从查询正文内部引发的异常。假定SomeMethodThatMightThrow 可能导致要求停止执行查询的异常。

请注意,try 块将 foreach 循环而不是查询本身封闭起来这是因为 foreach 循环是实际执行查询的场所。

class QueryThatThrows{    static void Main()    {        // Data source.        string[] files = { "fileA.txt", "fileB.txt", "fileC.txt" };        // Demonstration query that throws.        var exceptionDemoQuery =            from file in files            let n = SomeMethodThatMightThrow(file)            select n;        // Runtime exceptions are thrown when query is executed.        // Therefore they must be handled in the foreach loop.        try        {            foreach (var item in exceptionDemoQuery)            {                Console.WriteLine("Processing {0}", item);            }        }        // Catch whatever exception you expect to raise        // and/or do any necessary cleanup in a finally block        catch (InvalidOperationException e)        {            Console.WriteLine(e.Message);        }        //Keep the console window open in debug mode        Console.WriteLine("Press any key to exit");        Console.ReadKey();    }    // Not very useful as a general purpose method.    static string SomeMethodThatMightThrow(string s)    {        if (s[4] == 'C')            throw new InvalidOperationException();        return @"C:\newFolder\" + s;    }}/* Output:    Processing C:\newFolder\fileA.txt    Processing C:\newFolder\fileB.txt    Operation is not valid due to the current state of the object. */


0 0
原创粉丝点击