Using C# LINQ - A Practical Overview

player_one
5,312 views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

LINQ Concepts - Method syntax

The other LINQ format is method syntax. LINQ method syntax can do everything that query syntax can do, and more. It's just a different way to format the instructions.

Method syntax example

Recall this example of query syntax from the previous lesson:

List<string> animalNames = new List<string>
    {"fawn", "gibbon", "heron", "ibex", "jackalope"};
    
// Result: {"heron", "gibbon", "jackalope"}
IEnumerable<string> longAnimalNames =
    from name in animalNames
    where name.Length >= 5
    orderby name.Length
    select name;

The exact same instruction set can be written using method syntax like this:

List<string> animalNames = new List<string>
    {"fawn", "gibbon", "heron", "ibex", "jackalope"};

IEnumerable<string> longAnimalNames =
    animalNames
    .Where(name => name.Length >= 5)
    .OrderBy(name => name.Length);

NOTE: The spaces, tabs, and linebreaks in these examples are just whitespace, used for formatting, and are not syntactically important.

Advantages of method syntax

Personally, I prefer method syntax over query syntax, and this is the format that will be used for the rest of this course. Here are some of the advantages of method syntax:

  • Query syntax is automatically converted to method syntax at compilation time
  • Not all LINQ methods can be utilized with query syntax
  • Method syntax is stylistically more similar to other C# code

Method syntax exercise

This is the exact same exercise as in the previous lesson. Now try to write it with method syntax.

The following code shows a LINQ query that returns the input inValues unmodified. Using the format of the example above, see if you can return only the strings that have pattern in them (using the String.Contains() method) and order the list alphabetically.

Method Syntax Exercise
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using System.Collections.Generic;
using System.Linq;
namespace MethodSyntax1
{
public static class MethodSyntax1
{
public static IEnumerable<string> FilterAndSort(IEnumerable<string> inValues, string pattern)
{
return inValues
// LINQ method calls here
;
}
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content