linq select
时间: 2023-11-01 15:56:09 浏览: 97
C#/.NET - LInq中SelectMany方法
5星 · 资源好评率100%
LINQ (Language-Integrated Query) is a feature in C# that allows developers to query and manipulate data from various data sources using a unified syntax. The `select` clause in LINQ is used to perform projections, which means selecting specific properties or transforming the original data into a new shape.
Here's an example of using the `select` clause in LINQ:
```csharp
// Assume we have a list of Person objects
List<Person> people = new List<Person>
{
new Person { Name = "John", Age = 30 },
new Person { Name = "Jane", Age = 25 },
new Person { Name = "Bob", Age = 40 }
};
// Selecting only the names of people
var names = people.Select(p => p.Name);
// Selecting a new object with transformed properties
var transformedPeople = people.Select(p => new { FirstName = p.Name, BirthYear = DateTime.Now.Year - p.Age });
foreach (var name in names)
{
Console.WriteLine(name);
}
foreach (var person in transformedPeople)
{
Console.WriteLine($"Name: {person.FirstName}, Birth Year: {person.BirthYear}");
}
```
In the above example, the `select` clause is used to extract the `Name` property from each `Person` object and store it in the `names` variable. It is also used to create a new anonymous object with transformed properties (`FirstName` and `BirthYear`) based on the original data.
Note that the `select` clause works with different LINQ methods such as `Select`, `SelectMany`, etc., to perform various kinds of projections and transformations on data.
阅读全文