One way to use LINQ is via LINQ to Objects, which allows you to query collections
of objects. You can use LINQ to query any collection that implements the IEnumerable
interface. As you may recall, we discussed interfaces in Chapter 4; now you can see one
more example of how important interfaces are to .NET development. Listing 1 shows
a program that uses LINQ to query a collection. The object type is a custom class, named
Customer. The Main method creates a generic list of Customer and uses a LINQ query to
extract the Customer objects that have a first name that starts with the letter M.
Listing 1 A program demonstrating how to make a LINQ to objects query
C#:
using System;
using System.Collections.Generic;
using System.Linq;
class Customer
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
class Program
{
static void Main(string[] args)
{
List<Customer> custList = new List<Customer>
{
new Customer
{
FirstName = "Joe",
LastName = "Zev"
},
new Customer
{
FirstName = "May",
LastName = "Lee"
},
new Customer
{
FirstName = "Meg",
LastName = "Han"
}
};
var customers =
from cust in custList
where cust.FirstName.StartsWith("M")
select cust;
foreach (var cust in customers)
{
Console.WriteLine(cust.FirstName);
}
Console.ReadKey();
}
}
To
clarify, the following examples show both the C# LINQ query:
var customers =
from cust in custList
where cust.FirstName.StartsWith("M")
select cust;
The customers variable in the LINQ queries references a new collection that holds the
result of running the LINQ query, which contains all of the customers where the first letter
of the FirstName property is the letter M. The from clause specifies the range variable
that you name, cust is the name I chose, and the collection object to query, custList, was
created and populated in the previous line of code. The range variable is what you use to
specify parameters of the LINQ query. In the preceding example, we use the where clause
to filter the results of the query. This where clause calls the StartsWith method on each
FirstName property of the cust range variable to specify the filter.
No comments :
Post a Comment