Linq and C# Lambda expressions

What is Linq

Introduction

Linq (Language Integrated Query) is a language-integrated query technology that can be used in C# and other .NET languages. Linq allows us to use a SQL-like language to query data, which makes the code more concise and easier to read. Linq provides a general query interface that can be used to query various data sources, including collections, databases, XML documents, and Web services.

Advantages of Linq

The advantage of Linq is that it simplifies data access and query operations. Linq allows us to use a unified syntax to process various data sources, which makes the code more concise, easy to maintain and expand. Linq also provides a strongly typed query method, which can check the correctness of the query statement at compile time, avoiding runtime errors.

In addition, Linq also provides some convenient extension methods, which can perform various operations on collections and other data sources, including filtering, sorting, grouping, aggregation, etc. These methods are usually combined in a chained way, which allows us to easily build complex query statements.

Application scenarios of Linq

Linq is widely used in various programming scenarios. Here are some common application scenarios:

database access

Linq can be integrated with various databases, including SQL Server, Oracle, MySQL, etc. Through Linq, we can use a unified syntax to query the data in the database without writing complex SQL statements. Linq also provides some convenient methods to add, delete, and modify the database.

collection processing

Linq can be used to process various collections, including arrays, lists, dictionaries, etc. Through Linq, we can easily perform operations such as filtering, sorting, grouping, and aggregation on collections. These methods are usually combined in a chained way, which allows us to easily build complex query statements.

XML processing

Linq can be used to process XML documents. Through Linq, we can use a syntax similar to XPath to query data in XML documents. Linq also provides some convenient methods for adding, deleting, and modifying XML documents.

database access

Here is an example of accessing a database using Linq, assuming we have a Persontable called Nameand Agetwo fields:

var db = new DataContext();
var query = from p in db.Person
            where p.Age > 18
            orderby p.Name
            select p;
foreach (var person in query)
{
    Console.WriteLine($"{person.Name}, {person.Age}");
}

The code above uses Linq to query for people whose age is greater than 18, sorted by name. Among them, DataContextis a DbContextcustom class inherited from, which is used to connect to the database and operate the data table.

collection processing

Here's an example of working with collections using Linq, assuming we have a numberslist called , which contains some integers:

var numbers = new List<int> { 1, 2, 3, 4, 5 };
var query = from n in numbers
            where n % 2 == 0
            orderby n descending
            select n;
foreach (var number in query)
{
    Console.WriteLine(number);
}

The above code uses Linq to find even numbers in the list and outputs them in reverse order. Among them, fromkeywords are used to specify the data source to be queried, wherekeywords are used to filter data, orderbykeywords are used to sort data, and selectkeywords are used to select data to be output.

XML processing

Here is an example of using Linq to process an XML document, assuming we have an students.xmlXML document called , which contains information about some students:

<?xml version="1.0" encoding="utf-8"?>
<students>
  <student name="Alice" age="18" gender="female" />
  <student name="Bob" age="20" gender="male" />
  <student name="Charlie" age="22" gender="male" />
</students>

We can use Linq to query the names and genders of students older than 18:

var doc = XDocument.Load("students.xml");
var query = from student in doc.Descendants("student")
            where (int)student.Attribute("age") > 18
            select new
            {
                Name = (string)student.Attribute("name"),
                Gender = (string)student.Attribute("gender")
            };
foreach (var student in query)
{
    Console.WriteLine($"{student.Name}, {student.Gender}");
}

The above code uses Linq to query the student information in the XML document, and selects the data to be output according to the condition. Among them, XDocumentis a class used to represent an XML document, Descendantsthe method is used to query all elements in the document, and Attributethe method is used to obtain the attribute value of the element.

Linq is a powerful and flexible query technology that can help us simplify data access and query operations. Whether in scenarios such as database access, collection processing, or XML processing, Linq can provide a simple and unified syntax to process data. If you have not mastered Linq technology, it is recommended that you learn and apply it in actual development as soon as possible.

Lambda expression

Lambda expression is a new language feature introduced by C# 3.0, which allows us to define anonymous functions in the code. The general form of a Lambda expression is x => expressionwhere xdenotes the parameter list and expressiondenotes the function body. Lambda expressions can be used in a variety of scenarios, including Linq queries, event handling, delegation, and more.

The relationship between Lambda expression and Linq

Lambda expressions and Linq are inseparable, they can be used together to build complex query statements. Since Linq provides a unified query interface, we can use Lambda expressions to define query conditions and selected data. Here is an example of a Linq query using Lambda expressions, assuming we have a numberslist called , which contains some integers:

var numbers = new List<int> { 1, 2, 3, 4, 5 };
var query = numbers.Where(n => n % 2 == 0).OrderByDescending(n => n);
foreach (var number in query)
{
    Console.WriteLine(number);
}

The above code uses Lambda expressions to define query conditions and sorting methods, Wherethe method is used to filter data, and OrderByDescendingthe method is used to sort data in reverse order.

Concrete examples of using Lambda expressions

Here is a concrete example using Lambda expressions, assuming we have a peoplelist named , which contains information about some people:

var people = new List<Person>
{
    new Person { Name = "Alice", Age = 18, Gender = Gender.Female },
    new Person { Name = "Bob", Age = 20, Gender = Gender.Male },
    new Person { Name = "Charlie", Age = 22, Gender = Gender.Male }
};
var query = people.Where(p => p.Age > 18 && p.Gender == Gender.Male).OrderBy(p => p.Name);
foreach (var person in query)
{
    Console.WriteLine($"{person.Name}, {person.Age}, {person.Gender}");
}

The code above uses a Lambda expression to filter people who are older than 18 and whose gender is male, and sort by name. Among them, Wherethe method uses Lambda expression to define the query condition, and OrderBythe method uses Lambda expression to define the sorting method. These lambda expressions make the code more concise and easier to read.

Linq is a powerful and flexible query technology that can help us simplify data access and query operations. Whether in scenarios such as database access, collection processing, or XML processing, Linq can provide a simple and unified syntax to process data. If you have not mastered the technology of Linq and Lambda expressions, it is recommended that you learn and apply them in actual development as soon as possible.

Guess you like

Origin blog.csdn.net/Documentlv/article/details/130766808