【问题标题】:Creation of a list with array in C#在 C# 中使用数组创建列表
【发布时间】:2018-04-21 11:00:56
【问题描述】:

我正在查询多个表,结果我得到类似于以下列表的结果:

[{
    "$id": "7",
    "idPoiType": 43,
    "latPoint": 40.522053118634076,
    "lngPoint": -3.665313720703125
},
{
    "$id": "8",
    "idPoiType": 43,
    "latPoint": 40.52172689430316,
    "lngPoint": -3.6571168899536133
}]

我尝试从第一个列表创建具有以下格式的第二个列表

[{
    "idPoiType": 43,
    "point": [{40.522053118634076, -3.665313720703125}, {40.52172689430316, -3.6571168899536133}]
}]

为此,我有两个模型和以下查询

模型

    public class ChildPoints
    {
        public double latPoint { get; set; }
        public double lngPoint { get; set; }
    }

    public class RootPoints
    {
        public int idPoiType { get; set; }
        public List<ChildPoints> point { get; set; }
    }

查询

        var result1 = (
        from p in result
        group p by new
        {
            p.idPoiType,
        } into g
        select new RootPoints()
        {
            idPoiType = g.Key.idPoiType,
            point = (from p2 in g
                     select new ChildPoints()
                     {
                         latPoint = p2.latPoint,
                         lngPoint = p2.lngPoint
                     })
        }
        ).ToList();

错误

Gravedad Código 描述 Proyecto Archivo Línea Estado suprimido 错误 CS0266 没有“System.Collections.Generic.IEnumerable”和“System.Collections.Generic.List”。 Ya existse una conversión explícita (compruebe si le falta una conversión) WebApplication1

我怎样才能做出正确的查询,以免出现错误,或者有没有其他方法可以在没有查询的情况下获取第二个列表?

【问题讨论】:

标签: c# arrays list linq group-by


【解决方案1】:

问题是Select 返回一个IEnumerable&lt;T&gt;,而RootPoints.point 是一个List&lt;T&gt;。尽管每个List&lt;T&gt; 都是IEnumerable&lt;T&gt;,但反之则不然。

您可以通过添加另一个 ToList 来解决此问题:

var result1 = (
     from p in result
     group p by new
     {
         p.idPoiType,
     } into g
     select new RootPoints()
     {
         idPoiType = g.Key.idPoiType,
         point = (from p2 in g
                  select new ChildPoints()
                  {
                      latPoint = p2.latPoint,
                      lngPoint = p2.lngPoint
                  }).ToList() // << here
     }
     ).ToList();

顺便说一句,大多数人都使用属性名大写和类名单数的约定,除非它们是事物的集合:

public class ChildPoint
{
    public double Latitude { get; set; }
    public double Longitude { get; set; }
}

public class RootPoint
{
    public int IdPoiType { get; set; }
    public List<ChildPoints> Points { get; set; }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-03
    • 1970-01-01
    • 1970-01-01
    • 2014-07-12
    • 2016-09-24
    • 1970-01-01
    • 2011-04-18
    • 1970-01-01
    相关资源
    最近更新 更多