c# - 使用 LINQ 选择数据到嵌套类

标签 c# linq

我有一个模型类:

public class Coordinate
{
    public decimal Xcoor { get; set; }
    public decimal Ycoor { get; set; }
}

那我还有一个类:

public class SectionCoordinateViewModel
{
    public SectionCoordinateViewModel()
    {
        this.Coordinate = new Coordinate();
    }
    public string SectionId { get; set; }
    public Coordinate Coordinate { get; set; }
}

然后我使用 LINQ 从数据库中收集数据:

var section = sectionService.getAll();
var data = from t in section
           select new SectionCoordinateViewModel
           {
               SectionId = "section_" + t.Id,
               //how to send data to Coordinate.Xcoor and Coordinate.Ycoor
           };

如何将它们发送到坐标?谢谢你

最佳答案

我假设您在 t 中有 XY 属性。您只需要初始化 Coordinate 对象并使用 object initializer设置 XcoorYcoor 属性。与您对 SectionCoordinateViewModel 所做的相同:

var data = from t in section
           select new SectionCoordinateViewModel
           {
               SectionId = "section_" + t.Id,
               Coordinate = new Coordinate
               {
                  Xcoor = t.X,
                  Ycoor = t.Y
               }
            };

注意:尝试改进变量的命名。例如。你应该使用 sections 而不是 section,因为你从服务中获取所有部分。不是一个人。您可以使用 s 代替 t,它代表 section 的第一个字母。您可以使用 models 之类的东西代替 data。您也不需要 coor 坐标属性中的后缀。顺便说一句,Point 可能更适合 Coordinate 类的名称。

关于c# - 使用 LINQ 选择数据到嵌套类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33098617/

相关文章:

c# - 将类型 `System.Collections.IEnumerator` 转换为 `System.Collections.Generic.IEnumerator`

c# - 您如何在连接中包含第一个表中的所有字段,以及剩余的一些字段?

c# - 返回匿名类型的简单方法(使使用 LINQ 的 MVC 成为可能)

c# - 检查表是否包含重叠的时间跨度

sql - 在同一字段上使用 And 运算符的 Linq to Sql

c# - EF Core Azure Cosmos DB 提供程序与 Cosmos LINQ to SQL 转换

c# - Visual Studio 2010 性能分析可以与用 C# 编写的 Windows 服务一起使用吗

c# - EPPlus 生成的 Excel 已损坏

c# - 如何让组合框重新测量项目高度?

c# - 如何将Web api小数结果格式化为两位小数