LINQ : LINQ Queries

LINQ is based on a set of query operators, defined as extension methods, that mainly work with any object that implements IEnumerable<T>. (For more details about extension methods,This approach makes LINQ a general-purpose querying framework because many lists implement IEnumerable<T>, and any developer can implement his or her own. This query infrastructure is also very extensible. Given the architecture of extension methods, developers can specialize a method's behavior based on the type of data they are querying. For instance,

LINQ to SQL and LINQ to XML have specialized LINQ operators to handle relational data and XML nodes, respectively.

Query Syntax

To understand query syntax, we will start with a simple example. Consider the following Developer type:
public class Developer {
public string Name;
public string Language;
public int Age;
}

Imagine that you need to query an array of objects of the Developer type, using LINQ to Objects, extracting the developers who use C# as their main programming language.
using System;
using System.Linq;
using System.Collections.Generic;
class app {
static void Main() {
Developer[] developers = new Developer[] {
new Developer {Name = "Paolo", Language = "C#"},
new Developer {Name = "Marco", Language = "C#"},
new Developer {Name = "Frank", Language = "VB.NET"}};
IEnumerable<string> developersUsingCsharp =
from d in developers
where d.Language == "C#"
select d.Name;
foreach (string item in developersUsingCsharp) {
Console.WriteLine(item);
}
}
}
The result of running this code would be the developers Paolo and Marco.

No comments:

Post a Comment