📅  最后修改于: 2023-12-03 15:29:45.138000             🧑  作者: Mango
C# LINQ (Language Integrated Query) provides a simple way to write concise and efficient queries against various data sources such as collections, databases, and XML documents.
One common operation in LINQ is to filter a data source based on a specific condition using the Where
method. The Where
method returns a new sequence of elements that satisfy the specified condition.
Here's an example of using the Where
method to filter a list of integers:
var numbers = new List<int> { 1, 2, 3, 4, 5 };
var evenNumbers = numbers.Where(n => n % 2 == 0);
foreach (var number in evenNumbers)
{
Console.WriteLine(number);
}
In this example, we create a list of integers and then use the Where
method to create a new sequence of even numbers. The Where
method takes a lambda expression that specifies the condition to filter on. In this case, we use the modulo operator to check if the number is even.
We can also use the Where
method to filter a sequence of objects based on a property value. Here's an example:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
var people = new List<Person>
{
new Person { Name = "John", Age = 25 },
new Person { Name = "Jane", Age = 30 },
new Person { Name = "Bob", Age = 40 }
};
var youngPeople = people.Where(p => p.Age < 30);
foreach (var person in youngPeople)
{
Console.WriteLine(person.Name);
}
In this example, we create a list of Person
objects and then use the Where
method to create a new sequence of people who are younger than 30. We use a lambda expression to specify the condition to filter on, which is p.Age < 30
.
We can also use the Select
method to project the elements of a sequence into a new form. Here's an example:
var names = people.Select(p => p.Name);
foreach (var name in names)
{
Console.WriteLine(name);
}
In this example, we use the Select
method to create a new sequence of just the names of the Person
objects. We use a lambda expression to specify the projection, which is p.Name
.
In summary, the Where
method is used to filter a data source based on a specific condition, while the Select
method is used to project the elements of a sequence into a new form. These two methods are commonly used together in LINQ queries to efficiently retrieve only the data that is needed.