Language-Integrated Query (LINQ) is the name for a set of technologies based on the integration of query capabilities directly into the C# language.
Traditionally, queries against data are expressed as simple strings without type checking or IntelliSense support at compile time. Also, you need to know a different query language for each data source: SQL databases, XML documents, web applications, and so on. In LINQ, the query consists of preliminary language structures, such as classes, methods, and events.
When writing queries, the most visible "language-integrated" part of LINQ is the query specification. Question words are written in declarative question syntax. Using query syntax you perform filtering, sorting, and grouping over data sources with minimal code. We use the same query definition pattern to query and modify data from any data source.
The following example shows a complete query function. The entire process includes creating the data source, defining the query definition, and executing the query in the foreach statement.
csharpusing System; using System.Collections.Generic; using System.Linq; public class example { public static void Main(string[] args) { // Specify the data source. int[] scores = new int[] { 97, 92, 81, 60 }; // Define the query expression. IEnumerable<int> scoreQuery = from score in scores where score > 80 select score; // Execute the query. foreach (var i in scoreQuery) { Console.Write(i + " "); } // Output: 97 92 81 } }
Output
Key concepts in LINQ:
Data Source: LINQ can query various types of data sources, such as:
Query Expression: The query expression defines the logic to retrieve the data from the data source.
Execution: Once the query is defined, it can be executed by using loops (foreach) or other operators.
The following example illustrates the LINQ Method Syntax.
csharpusing System; using System.Linq; using System.Collections.Generic; class Program { static void Main() { // Data source List<int> scores = new List<int>() { 97, 92, 81, 60 }; // Define the query using method syntax IEnumerable<int> scoreQuery = scores.Where(score => score > 80); // Execute the query foreach (int score in scoreQuery) { Console.WriteLine(score); } } }
Output
The following are the common Methods of the LINQ:
csharpvar filtered = collection.Where(item => item > 10);
csharpvar projected = collection.Select(item => item * 2);
csharpvar ordered = collection.OrderBy(item => item);
csharpvar grouped = collection.GroupBy(item => item % 2);
csharpvar joined = collection1.Join(collection2, item1 => item1.Key, item2 => item2.Key, (item1, item2) => new { item1, item2 });
LINQ is a powerful C# tool widely used to query and manipulate data with minimal complex code.
Copyrights © 2024 letsupdateskills All rights reserved