C# language feature:

  • Query expressions

applies to

  • IEnumerable<T> or IQueryable<T> collection

benefit

  • Use query expressions to retrieve a
  • 1) subset of the elements.
  • 2) singleton value about the source data.
  • 3) sequence of elements and transform them to a new type of object.

how to use

  • A query expression must begin with a from clause and must end with a select or group clause.Between the first from clause and the last select or group clause, it can contain one or more of these

optional clauses

  • where, orderby, join let and even additional from clauses. You can also use the intokeyword to enable the result of a join or group clause to serve as the source for additional query clauses in the same query expression.

note

  • For more on query expressions, please see https://docs.microsoft.com/en-us/dotnet/articles/csharp/linq/query-expression-basics

example:

        static void RetrieveSubset()
        {
            // Data source.
            int[] temperatures = { 75, 77, 84, 83, 76, 83 };

            // Declare the query Expression.
            IEnumerable<int> temperatureQuery = //query variable
                from temperature in temperatures //required
                where temperature > 78 // optional criteria
                orderby temperature descending // optional ordering
                select temperature; //must end with select or group

            // Execute the query
            foreach (int temperature in temperatureQuery)
            {
                Console.WriteLine(temperature);
            }

            // Retrieve a singleton value about the source data
            int hightemperatureCount = temperatureQuery.Max();

            //  Retrieve a sequence of elements and transform them to a new type of object
            // Declare the query Expression.
            IEnumerable<int> ConverttoCelcius= //query variable
                from temperature in temperatures //required
                select (temperature - 32) *( 5 / 9); //must end with select or group

            // Execute the query
            foreach (int temperature in ConverttoCelcius)
            {
                Console.WriteLine(temperature);
            }

        }