[LINQ] LINQ – What is it?

LINQ is about data queries. Programmers usually use separate ways to manipulate data based on the underlying data formats. You used ADO.NET for databases and XML DOM for XML documents. LINQ is designed to provide a single approach to manipulate data regardless of data formats.         

 

1. LINQ Components

You can use LINQ to many different data types.

  • LINQ to Objects: performs queries against in-memory collections and is based on “IEnumerable(System.Linq)
  • LINQ to XML: works with XML documents or elements (System.Xml.Linq)
  • LINQ to DataSet: works with legacy “DataSet” objects
  • LINQ to SQL: works with MS SQL Server databases and is based on “IQueryable(System.Data.Linq)
  • LINQ to Entities: works with Entity Framework

 

2. C# Features for LINQ

C# 3 introduced a couple of new features, which are mainly associated with LINQ.

  • Implicitly typed local variables (var)
  • Object/Collection initialization syntax
  • Lambda expressions
  • Extension methods
  • Anonymous types

 

3. Syntax of LINQ

There are 2 ways to use LINQ:

  • Standard Query Operators (dot notation)
  • Query Expressions: SQL like syntax
var sequence = employees.Where(e => e.ID  e);
var sequence = from e in employees
  where (e.ID < 10)
  select e;

 

4. LINQ to Legacy Collections

LINQ can be called on collections based on “IEnumerable<T>“. The legacy non-collections do not implement this interface. The solution is to convert legacy collections to “IEnumerable<T>sequences.

There are 2 operators for this purpose:

  • Cast
  • OfType
public static IEnumerable<T> Cast<T>(this IEnumerable source);
public static IEnumerable<T> OfType<T>(this IEnumerable source);
  • The “Castoperator will attempt to cast every element to the specified type and exception will be thrown when the cast fails.
  • The “OfTypeoperator will store only objects of the specified type in the output sequence and no exception will be thrown.

 

5. Tips

  • Use “var” when you do not know the return type of a LINQ Query (and then you can get the type with the “GetType()” method and replace it if you want)
  • Prefer “OfTYpeto “Cast
  • Careful with deferred queries

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s