Sqlce WP from query statement details

Source: Internet
Author: User
Http://msdn.microsoft.com/zh-cn/library/bb383978 (V = vs.110). aspxfrom clause (C # reference) Visual Studio 2012In other versions, this topic has not been rated.-comment on this topic.

[This document is for preview only and may be changed in future releases. Blank topics are used as placeholders.]

The query expression must start with the from clause. In addition, the query expression can contain subqueries, which also start with the from clause. The from clause specifies the following content:

  • The data source that runs the query or subquery on it.

  • A local range variable that represents each element in the source sequence.

Both range variables and data sources are strongly typed. The data source referenced in the from clause must be of ienumerable, ienumerable <t>, or a derived type (such as iqueryable <t> ).

In the following example, numbers is the data source, and num is the range variable. Note that both variables are strongly typed, even if the VaR keyword is used.

C #
class LowNums{    static void Main()    {           // A simple data source.        int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };        // Create the query.        // lowNums is an IEnumerable<int>        var lowNums = from num in numbers            where num < 5            select num;        // Execute the query.        foreach (int i in lowNums)        {            Console.Write(i + " ");        }    }        }// Output: 4 1 3 2 0
Range variable

If the data source implements ienumerable <t>, the compiler can infer the type of the range variable. For example, if the data source type isIenumerable <customer>, It is inferred that the type of the range variable is customer. Only when the data source is non-genericIenumerableData Source Type (such as arraylist) must be explicitly specified. For more information, see How to query arraylist using LINQ.

In the previous example, num is inferred to be of the int type. Because the range variable is strongly typed, you can call a method or use it in other operations. For example, you can write select num instead of select num. tostring () so that the query expression returns a string sequence instead of an integer sequence. Alternatively, you can write select N + 10 to return the sequence 14, 11, 13, 12, and 10. For more information, see select clause (C # reference ).

The range variable is similar to the iteration variable in the foreach statement, but there is a very important difference between the two: the range variable never actually stores data from the data source. The range variable only provides syntax convenience, so that the query can describe what will happen when the query is executed. For more information, see section C #).

Compound from clause

In some cases, each element in the source sequence may be a sequence or contain a sequence. For example, the data source may beIenumerable <student>Each student object in the sequence contains a quiz score list. To access the internal list of each student element, you can use the composite from clause. This technique is similar to using nested foreach statements. You can add a where or orderby clause to any from clause to filter the results. The following example demonstrates a sequence of student objects. Each object contains an internal integer list that represents the test score. To access the internal list, this example uses the composite from clause. If necessary, you can insert a sub-statement between two from clauses.

C #
class CompoundFrom{    // The element type of the data source.    public class Student    {        public string LastName { get; set; }        public List<int> Scores {get; set;}    }    static void Main()    {        // Use a collection initializer to create the data source. Note that         // each element in the list contains an inner sequence of scores.        List<Student> students = new List<Student>        {           new Student {LastName="Omelchenko", Scores= new List<int> {97, 72, 81, 60}},           new Student {LastName="O'Donnell", Scores= new List<int> {75, 84, 91, 39}},           new Student {LastName="Mortensen", Scores= new List<int> {88, 94, 65, 85}},           new Student {LastName="Garcia", Scores= new List<int> {97, 89, 85, 82}},           new Student {LastName="Beebe", Scores= new List<int> {35, 72, 91, 70}}         };                // Use a compound from to access the inner sequence within each element.        // Note the similarity to a nested foreach statement.        var scoreQuery = from student in students                         from score in student.Scores                            where score > 90                            select new { Last = student.LastName, score };        // Execute the queries.        Console.WriteLine("scoreQuery:");        // Rest the mouse pointer on scoreQuery in the following line to         // see its type. The type is IEnumerable<'a>, where 'a is an         // anonymous type defined as new {string Last, int score}. That is,        // each instance of this anonymous type has two members, a string         // (Last) and an int (score).        foreach (var student in scoreQuery)        {            Console.WriteLine("{0} Score: {1}", student.Last, student.score);        }        // Keep the console window open in debug mode.        Console.WriteLine("Press any key to exit.");        Console.ReadKey();    }       }/*scoreQuery:Omelchenko Score: 97O'Donnell Score: 91Mortensen Score: 94Garcia Score: 97Beebe Score: 91*/
Use multiple from clauses to perform join operations

The composite from clause is used to access the internal set of a single data source. However, a query can contain multiple from clauses that can be used to generate supplementary queries from an independent data source. This technique can be used to perform certain types of join operations that cannot be performed by using the join clause.

The following example shows how to use two from clauses to form a full cross join between two data sources.

C #
class CompoundFrom2{    static void Main()    {        char[] upperCase = { 'A', 'B', 'C' };        char[] lowerCase = { 'x', 'y', 'z' };        // The type of joinQuery1 is IEnumerable<'a>, where 'a        // indicates an anonymous type. This anonymous type has two        // members, upper and lower, both of type char.        var joinQuery1 =            from upper in upperCase            from lower in lowerCase            select new { upper, lower };        // The type of joinQuery2 is IEnumerable<'a>, where 'a        // indicates an anonymous type. This anonymous type has two        // members, upper and lower, both of type char.        var joinQuery2 =            from lower in lowerCase            where lower != 'x'            from upper in upperCase            select new { lower, upper };        // Execute the queries.        Console.WriteLine("Cross join:");        // Rest the mouse pointer on joinQuery1 to verify its type.        foreach (var pair in joinQuery1)        {            Console.WriteLine("{0} is matched to {1}", pair.upper, pair.lower);        }        Console.WriteLine("Filtered non-equijoin:");        // Rest the mouse pointer over joinQuery2 to verify its type.        foreach (var pair in joinQuery2)        {            Console.WriteLine("{0} is matched to {1}", pair.lower, pair.upper);        }        // Keep the console window open in debug mode.        Console.WriteLine("Press any key to exit.");        Console.ReadKey();    }}/* Output:        Cross join:        A is matched to x        A is matched to y        A is matched to z        B is matched to x        B is matched to y        B is matched to z        C is matched to x        C is matched to y        C is matched to z        Filtered non-equijoin:        y is matched to A        y is matched to B        y is matched to C        z is matched to A        z is matched to B        z is matched to C        */

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.