C# LINQ


LINQ Query Syntax
The following example uses LINQ to create a query to find some data in a simple in-memory array of objects and print them to the console. First, you need to reference the System.Linq namespace. The LINQ query starts by declaring a variable to hold the results of the query which is usually done by declaring a variable with the var keyword. var is a keyword in C# created to declare a general variable type. The var keyword tells the compiler to infer the type of the result based on the query. The name queryResults is arbitrary. You can call it whatever you like within the rules of variable naming. The rest of the query is deliberately similar to SQL language. The n is just a stand-in for an individual element in the data source. A LINQ data source must be enumerable (an array of collection of items). The data source cannot be a single value or object, such as a single int value. The result, of course, may end up being a single item.

using System;     // LINQ Syntax
using System.Collections.Generic;
using System.Linq;  // add this!
using System.Text;
using System.Threading.Tasks;
using static System.Console;

namespace BegVCSharp_20_3_QuerySyntax  {
    class Program
    {
        static void Main(string[] args)  {
            string[] names = { "Alonso", "Zheng",
                "Smith", "Jones", "Smythe", "Small",
                "Ruiz", "Hsieh", "Jorgenson", "Ilyich",
                "Singh", "Samba", "Fatimah" };
            var queryResults =
                from n in names
                where n.StartsWith("S")
                orderby n
                select n;
            WriteLine("Names beginning with S:");
            foreach (var item in queryResults)  {
                WriteLine(item);  }
            Write("Press Enter/Return to end:");
            ReadLine();
        }
    }
}

The orderby clause defaults to ascending. If you want it sorted descending, then your clause would be orderby n descending. You can use expressions as well. To order by the last letter in the name then use the following: orderby n.Substring(n.Length – 1). Note that there is no guarantee of order beyond what is specified in the orderby clause.

The where clause takes any Boolean (true or false) expression that can be applied to the items in the data source. If you wanted a length greater than 10 you would use: where n.Length > 10. If you wanted only those containing the letter Q then you would use: where n.Contains(“Q”).

Leave a comment

Your email address will not be published. Required fields are marked *