150 likes | 254 Views
Introduction to LINQ. Language-Integrated Query. Queries. A query is an expression that retrieves data from a data source. Queries are usually expressed in a specialized query language.
E N D
Introduction to LINQ Language-Integrated Query
Queries • A query is an expression that retrieves data from a data source. • Queries are usually expressed in a specialized query language. • Developers have had to learn a new query language for each type of data source or data format that they support. • LINQ offers a consistent model for working with data across various kinds of data sources and formats. • In a LINQ query, you are always working with objects. • You use the same basic coding patterns to query and transform data in XML documents, SQL databases, ADO.NET Datasets, .NET collections, and any other format for which a LINQ provider is available.
Three Parts of a LINQ Query Operation • Obtain the data source • Create the query • Execute the query
static void Main() { // Data source. int[] scores = { 90, 71, 82, 93, 75, 82 }; // Query Expression. IEnumerable<int> scoreQuery = //query variable from score in scores //required where score > 80 // optional orderby score descending // optional select score; //must end with select or group // Execute the query to produce the results foreach (inttestScore in scoreQuery) { Console.WriteLine(testScore); } } // Outputs: 93 90 82 82
LINQ Data Source • A LINQ data source is any object that supports the generic IEnmerable<T> interface, or an interface that inherits from it. • With LINQ to SQL, first create an object-relational mapping at design time • Write your queries against the objects • at run-time LINQ to SQL handles the communication with the database.
LINQ Query • The query specifies what information to retrieve from the data source or sources. • Optionally, a query also specifies how that information should be sorted, grouped, and shaped before it is returned. • A query is stored in a query variable and initialized with a query expression. • To make it easier to write queries, C# has introduced new query syntax.
LINQ Query • In a LINQ query, the first step is to specify the data source. • In C# as in most programming languages a variable must be declared before it can be used. • In a LINQ query, the from clause comes first in order to introduce the data source (customers) and the range variable (cust). // Use of var is optional here and in all queries. //queryAllCustomers is an IEnumerable<Customer> varqueryAllCustomers = from cust in customers select cust;
Filtering • The most common query operation is to apply a filter in the form of a Boolean expression. • The filter causes the query to return only those elements for which the expression is true. //queryLondonCustomersis an IEnumerable<Customer> varqueryLondonCustomers = from cust in customers where cust.City == "London" select cust;
Filtering • You can use the familiar C# logical AND and OR operators to apply as many filter expressions as necessary in the where clause. where cust.City=="London" && cust.Name == "Devon" where cust.City == "London" || cust.City == "Paris"
Ordering • Sort the returned data using the orderby clause varqueryLondonCustomers3 = from cust in customers where cust.City == "London" orderbycust.Name ascending select cust;
select Clause • A simple select clause just produces a sequence of the same type of objects as the objects that are contained in the data source. IEnumerable<Country> sortedQuery = from country in countries orderbycountry.Area select country;
Selecting • The select clause can also be used to transform source data into sequences of new types. This transformation is also called a projection //queryAllCustomers is an IEnumerable<StoreCustomer> varqueryAllCustomers = from c in customers select new StoreCustomer { Name = c.Name, Address = c.Address, Email = c.Email, Phone = c.Phone };
Joining • In LINQ the join clause always works against object collections instead of database tables directly. varqueryCustomersDistributors= from cust in customers join dist in distributors on cust.City equals dist.City select new CustomerDistributor { CustomerName= cust.Name, DistributorName= dist.Name };
Query Execution //convert LINQ Query results to a list of ProductTypeobjects IList<DataContracts.ProductType> productTypes = etTypes.ToList(); //assign first element in a sequence, //or a default value if the sequence contains no elements ProductTypesomeProductType= etType.FirstOrDefault();
Query Syntax and Method Syntax //Query syntax IEnumerable<City> queryMajorCities = from city in cities where city.Population > 100000 select city; // Method-based syntax IEnumerable<City> queryMajorCities2 = cities.Where(c => c.Population > 100000);