CHAPTER 12 LINQ TO OBJECTS
Note The .NET Framework 4.5 SDK documentation provides full details regarding each of the C# LINQ
operators. Look up the topic “LINQ General Programming Guide” for more information.
Table 12-3. Common LINQ Query Operators
Query Operators
Meaning in Life
from, in
Used to define the backbone for any LINQ expression, which allows
you to extract a subset of data from a fitting container.
where
Used to define a restriction for which items to extract from a container.
select
Used to select a sequence from the container.
join, on, equals, into
Performs joins based on specified key. Remember, these “joins” do
not need to have anything to do with data in a relational database.
orderby, ascending, descending
Allows the resulting subset to be ordered in ascending or
descending order.
group, by
Yields a subset with data grouped by a specified value.
In addition to the partial list of operators shown in Table 12-3, the System.Linq.Enumerable class
provides a set of methods that do not have a direct C# query operator shorthand notation, but are
instead exposed as extension methods. These generic methods can be called to transform a result set in
various manners (Reverse<>(), ToArray<>(), ToList<>(), etc.). Some are used to extract singletons from a
result set, others perform various set operations (Distinct<>(), Union<>(), Intersect<>(), etc.), and still
others aggregate results (Count<>(), Sum<>(), Min<>(), Max<>(), etc.).
To begin digging into more intricate LINQ queries, create a new Console Application named
FunWithLinqExpressions. Next, you need to define an array or collection of some sample data. For this
project, you will make an array of ProductInfo objects, defined in the following code:
class ProductInfo
{
public string Name {get; set;}
public string Description {get; set;}
public int NumberInStock {get; set;}
}
public override string ToString()
{
return string.Format("Name={0}, Description={1}, Number in Stock={2}",
Name, Description, NumberInStock);
}
Now populate an array with a batch of ProductInfo objects within your Main() method:
458