HOW TO: Query Objects in LINQ Using VB.NET And C#

LINQ is a powerful component that Microsoft introduced into the .NET framework a few years ago. Since then, the syntax and ideology has been adopted by Java, PHP and Javascript. The concept behind it is adding database like querying into your code allowing you to select objects from collections in a tuned manner rather than iterate through collections and filtering things out. Let us say we have a simple SQL statement below which selects customers from a customer table based on their state:

SELECT Name,Address FROM Customer
WHERE State = ‘CA’

If you had the same data in your application represented by objects, you could do the same kind of query using LINQ. Here is some sample syntax for selecting objects from a collection based:

VB.NET

Dim q = From c In Customers
                  Where c.State = "CA"
                Select c.Name, c.Address

C#

IEnumerable q = from c in Customers
                               where c.State = "CA"
                               select c.Name, c.Address;

The performance scales very well, and I have almost replaced iterating at this point. If you are interested, click here for information on LINQ.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>