Freigeben über


LINQ – What You Need to Know First

Inspired while reading a book LINQ in Action.

Following are the essential topics for better understanding of LINQ:

  • Implicitly typed local variables. Variables declared with var, instead exact type, are implicitly typed local variables. From MSDN:

The var keyword instructs the compiler to infer the type of the variable from the expression on the right side of the initialization statement.

Example:

var processes = Process.GetProcesses()

Object initializers let you assign values to any accessible fields or properties of an object at creation time without having to explicitly invoke a constructor.

Example:

new { //OBJECT INITIALIZER
        process.Id,
        Name = process.ProcessName
    }

  • Lambda expressions. Lambda expressions use => operator that reads as “goes to”. From MSDN:

The left side of the lambda operator specifies the input parameters (if any) and the right side holds the expression or statement block. The lambda expression x => x * x is read "x goes to x times x." This expression can be assigned to a delegate type.

Example:

process => process.WorkingSet64 > 20 * 1024

  • Extension methods. Extension methods is a capability to add functionality to a type even when you do not have it – super cool. from MSDN:

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.

Example:

Original type:

public class MyType
{
    public void WriteToConole(string whatToWrite)
    {
        Console.WriteLine(whatToWrite);
    }
}

Extension – notice it is static method, and this in front of the first parameter which is actual type being extended:

public static class MyTypeExtension
{
    public static void WriteToConsoleTwice(this MyType mytype, string str)
    {
        mytype.WriteToConole(str);
        mytype.WriteToConole(str);
    }
}

Usage:

MyType mytype = new MyType();
mytype.WriteToConsoleTwice("Hello world");

  • Anonymous types. This is helpful when in the need of creating intermediary objects which happens a lot. From MSDN:

Anonymous types provide a convenient way to encapsulate a set of read-only properties into a single object without having to first explicitly define a type.

Example:

new { process.Id, Name = process.ProcessName}

Following is the complete example of all the features listed above:

static void Main(string[] args)
{
    DisplayProcesses();
    Console.ReadLine();
}
static void DisplayProcesses()
{
    //IMPLICITLY TYPE LOCAL VARIABLE
    var processes =
    Process.GetProcesses()
            //LAMBDA EXPRESSION
    .Where(process => process.WorkingSet64 > 20 * 1024)
    //EXTENSION METHOD
    .OrderByDescending(process => process.WorkingSet64)
    .Select(process => new
    //ANONYMOUS TYPE
    { //OBJECT INITIALIZER
        process.Id,
        Name = process.ProcessName
    });
    ObjectDumper.Write(processes,10,Console.Out);
}

The output from running the program is similar tot he following:

LINQ sample