使用 linq 在 c# 中将 GeoData 转换为 GeoJson

问题描述

这是我的实体:

public class TLandPoint
{
    [Key]
    public int gid { get; set; }
    public Point geom { get; set; }
    public long LandId { get; set; }
    [MaxLength(150)]
    public long SumSpace { get; set; }
    public long CLevelId { get; set; }
}

我从数据库中选择数据: TLandPointD 指向我班级中的同一实体

 var TLandPt = DBcontext.TLandPointSelect(p => new TLandPointDto
            {
                gid = p.gid,CLevelId = p.CLevelId,geom = (p.geom),LandId = p.LandId,SumSpace = p.SumSpace,}).ToList();

这行显示 List of data

现在

我想从 linq 的结果创建 geojson 与此列表相同

{
    "type": "FeatureCollection","features": [
        {
            "id": 6,"type": "Feature","geometry": {
                "type": "Point","coordinates": [
                    5721495.610660064,4222076.000807296
                ]
            },"properties": {
                "LandId": 5698,"SumSpace": 17335,"CLevelId": 12303020001
            }
        }
    ]
}

如何在 c# .net core 5 中将 Linq 结果转换为 geojson

解决方法

你可以创建一个这样的类

namespace CTLandPt 
{
    using System;
    using System.Collections.Generic;

    using System.Globalization;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Converters;

    public partial class Temperatures
    {
        [JsonProperty("type")]
        public string Type { get; set; }

        [JsonProperty("features")]
        public List<Feature> Features { get; set; }
    }

    public partial class Feature
    {
        [JsonProperty("id")]
        public long Id { get; set; }

        [JsonProperty("type")]
        public string Type { get; set; }

        [JsonProperty("geometry")]
        public Geometry Geometry { get; set; }

        [JsonProperty("properties")]
        public Properties Properties { get; set; }
    }

    public partial class Geometry
    {
        [JsonProperty("type")]
        public string Type { get; set; }

        [JsonProperty("coordinates")]
        public List<double> Coordinates { get; set; }
    }

    public partial class Properties
    {
        [JsonProperty("LandId")]
        public long LandId { get; set; }

        [JsonProperty("SumSpace")]
        public long SumSpace { get; set; }

        [JsonProperty("CLevelId")]
        public long CLevelId { get; set; }
    }
}

然后只需将 TLandPt 的结果映射或复制到 CTLandPt 的新对象