LINQ is a tool that is used to work with databases or servers, linking the world of objects with data. LINQ: (Language-Integrated Query) , can be used in C# and can be quite simple to work with in terms of syntax.
A basic example of LINQ in action is:
//All LINQ query operations consist of three distinct actions:
//Obtain the data source.
//Create the query.
//Execute the query.
// The Three Parts of a LINQ Query:
// 1. Data source.
int[] numbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 };
// 2. Query creation. This is the actual query by itself.
// numQuery is an IEnumerable<int>
var numQuery =
from num in numbers
//num is an int variable that defines the range, and search in the integer array
where (num % 2) == 0//heres the condition, this says to only write even numbers
select num;//select those and write (i.e. assign values to num and write)
// 3. Query execution.
foreach (int num in numQuery)
{
Console.Write("{0,1} ", num);
}
So not that bad in terms of syntax. Basically:
If you're working with an external data source:
//like text files, or databases...
XElement x = new XElement(@"C:\data.xml");//a data source
// Query for customers in London.
IQueryable<Customer> custQuery =
from cust in x.Customers
where cust.City == "London"
select cust;
Console.ReadLine();
A basic example of LINQ in action is:
//All LINQ query operations consist of three distinct actions:
//Obtain the data source.
//Create the query.
//Execute the query.
// The Three Parts of a LINQ Query:
// 1. Data source.
int[] numbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 };
// 2. Query creation. This is the actual query by itself.
// numQuery is an IEnumerable<int>
var numQuery =
from num in numbers
//num is an int variable that defines the range, and search in the integer array
where (num % 2) == 0//heres the condition, this says to only write even numbers
select num;//select those and write (i.e. assign values to num and write)
// 3. Query execution.
foreach (int num in numQuery)
{
Console.Write("{0,1} ", num);
}
So not that bad in terms of syntax. Basically:
- Get a data source
- create something to search, for example, int x = from here incollection, give a condition like (number must be so and so), then once it matches condition, select, and retrieve
If you're working with an external data source:
//like text files, or databases...
XElement x = new XElement(@"C:\data.xml");//a data source
// Query for customers in London.
IQueryable<Customer> custQuery =
from cust in x.Customers
where cust.City == "London"
select cust;
Console.ReadLine();
No comments:
Post a Comment