Home >Backend Development >C#.Net Tutorial >How to use LINQ to query data in C#
How to use LINQ to query data in C# requires specific code examples
LINQ (Language Integrated Query) is a powerful query language in C#, which can help Developers simplify querying and operating on data. This article will introduce how to use LINQ to query data in C# and provide specific code examples.
Before using LINQ to query data, we first need to define a data source. In the example of this article, we assume that there is a class named "Person" that contains two attributes: name and age.
class Person { public string Name { get; set; } public int Age { get; set; } }
Next, we can define a list to store multiple Person objects.
List<Person> people = new List<Person> { new Person { Name = "张三", Age = 20 }, new Person { Name = "李四", Age = 25 }, new Person { Name = "王五", Age = 30 }, new Person { Name = "赵六", Age = 30 }, };
Now, we can use LINQ to query the data. The following are several commonly used LINQ query examples:
var query1 = from person in people where person.Age >= 25 select person;
var query2 = from person in people where person.Name.Contains("三") select person;
var query3 = from person in people where person.Age == 30 orderby person.Name ascending select person;
var query4 = (from person in people where person.Age == 30 select person).Count();
var query5 = from person in people where person.Age >= 25 select person.Name;
In these examples, LINQ query expressions are used to define Inquire. The structure of the query expression consists of keywords such as "from", "where", "orderby", "ascending", "descending", and "select". Developers can use these keywords flexibly as needed.
Finally, we can obtain specific data by iterating the query results.
foreach (var person in query1) { Console.WriteLine("姓名:{0},年龄:{1}", person.Name, person.Age); }
The query results in the above code example are people aged 25 or above. After traversing the query results and outputting them, the names and ages of the qualified people will be printed.
The above is a basic example of using LINQ to query data. Developers can further refine query conditions and operations according to specific needs. LINQ can be used not only to query collection type data, but also to query various data sources such as databases. By using LINQ flexibly, the code can be made more concise and readable, and development efficiency can be improved.
The above is the detailed content of How to use LINQ to query data in C#. For more information, please follow other related articles on the PHP Chinese website!