LINQ to Objects Program in simple C# 3.0

Using LINQ to Objects with List<T>

List<Person> people = new List<Person>
{
{ ID = 1, IDRole = 1, LastName = "Chaudhari", FirstName= "New York"},
{ ID = 2, IDRole = 2, LastName = "HaresH", FirstName ="USA"}
};
var query = from p in people
where p.ID == 1
select new { p.FirstName, p.LastName };
ObjectDumper.Write(query);

Above, you define a collection of Person objects and insert a couple of elements. List<T> is a generic class that implements IEnumerable<T>, so it's suitable for LINQ querying. Next you declare a variable, query, to hold the result of a LINQ query. Don't worry about the var keyword right now; it will be discussed later in this chapter, in “Implicitly Typed Local Variables." You initialize query to a LINQ's query expression. The from clause specifies a data source. The variable p represents an object in the people collection. The where clause specifies a condition for selecting from the data source. You want to retrieve just the person whose ID equals 1, so you specify a Boolean expression, p.ID == 1. Finally, the select clause specifies what Person data you're interested in retrieving.

The ObjectDumper class is a convenient utility for producing formatted output. It has only one method, Write(), which has three overloads. (Both the ObjectDumper.cs source code and the ObjectDumper.dll assembly come with the LINQ download.) When you run the program you'll see the result in following

C:Windows\System32\cmd.exe
FirstName=HaresH LastName=Chaudhari
Press any key to continue . . .

This very simple example uses new features from C# 3.0. The first is a query expression that is similar to the one used in SQL and allows developers to use query language syntax that they are already accustomed to. When the compiler finds a query expression in the code, it transforms that expression into C# method calls.


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: