在LINQ中重新映射属性,可以使用Select
方法和匿名类型或自定义类型。以下是一个简单的示例:
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
List<Student> students = new List<Student>
{
new Student { Id = 1, Name = "张三", Age = 20 },
new Student { Id = 2, Name = "李四", Age = 22 },
new Student { Id = 3, Name = "王五", Age = 21 }
};
var result = students.Select(s => new { s.Id, s.Name, s.Age });
foreach (var item in result)
{
Console.WriteLine($"Id: {item.Id}, Name: {item.Name}, Age: {item.Age}");
}
}
}
class Student
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
在这个示例中,我们使用Select
方法将Student
对象的属性重新映射到一个匿名类型,并在foreach
循环中输出结果。
如果需要使用自定义类型,可以按照以下方式操作:
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
List<Student> students = new List<Student>
{
new Student { Id = 1, Name = "张三", Age = 20 },
new Student { Id = 2, Name = "李四", Age = 22 },
new Student { Id = 3, Name = "王五", Age = 21 }
};
var result = students.Select(s => new StudentDTO { Id = s.Id, Name = s.Name, Age = s.Age });
foreach (var item in result)
{
Console.WriteLine($"Id: {item.Id}, Name: {item.Name}, Age: {item.Age}");
}
}
}
class Student
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
class StudentDTO
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
在这个示例中,我们创建了一个名为StudentDTO
的自定义类型,并将Student
对象的属性重新映射到StudentDTO
对象。然后,在foreach
循环中输出结果。
希望这个答案能够帮助到您。
领取专属 10元无门槛券
手把手带您无忧上云