将复杂数据整理为单个对象

问题描述 投票:0回答:1

我正在尝试从组合物中提取数据并创建EventDto。我能够使用foreach做到这一点,但语法令人恐惧。有没有更好的方式编写此代码?

 public class EventDtO
 {
    public string Id { get; set; }
    public string Title { get; set; }
    public string CategoryTitle { get; set; }
    public DateTime DateTime { get; set; }
  }

这是我要从中获取数据的复杂对象

public class RootObject
{ 
    public List<Event> Events { get; set; }
}

public class Event
{
    public string Id { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public string Link { get; set; }
    public List<Category> Categories { get; set; }
    public List<Geometry> Geometries { get; set; }
}

public class Geometry
{
    public DateTime Date { get; set; }
    public string Type { get; set; }
    public List<object> Coordinates { get; set; }
}

    public class Category 
{ 
    public int Id { get; set; }
    public string Title { get; set; }
}

我想要的映射关系是

EventDto.Id-> Event.IdEventDto.Title-> Event.TitleEvent.CategoryTitle-> Category.TitleEvent.DateTime-> Geometry.Date

类别类将仅包含一个值,但是几何。日期可以具有多个值。

所以我想要的输出是:

标题类别日期“冰山B42”海冰湖2020-04-23T14:24:00Z“冰山B42”海冰湖2017-09-15T00:00:00Z

如果执行以下代码,我将能够获得正确的信息。

var Event = new List<EventDTO>();
foreach (var con in content.Events)
{
    var data = new EventDTO
    {
        Title = con.Title,
        Id = con.Id
    };

    foreach (var cat in con.Categories)
    {
        data.CategoriesTitle = cat.Title;
    }

    foreach (var geo in con.Geometries)
    {
        data.DateTime = geo.Date;
        Event.Add(data);
    }
}

json的示例

   {
        "id": "EONET_2881",
        "title": "Iceberg B42",
             "description": "",
        "categories": [
            {
                "id": 15,
                "title": "Sea and Lake Ice"
            }
        ]
        "geometries": [
            {
                "date": "2017-04-21T00:00:00Z",
                "type": "Point", 
                "coordinates": [ -107.19, -74.63 ]
            },
            {
                "date": "2017-09-15T00:00:00Z",
                "type": "Point", 
                "coordinates": [ -107.11, -74.08 ]
            }
        ]
    }
c#
1个回答
0
投票

您没有为每个Geometry创建一个新的EventDTO。这是否会导致最后一个记录的日期有多个记录?这是您要找的吗?

var Event = content.Events.SelectMany(con => 
    con.Geometries.Select(geo => 
        new EventDTO
        {
            Title = con.Title,
            Id = con.Id,
            CategoriesTitle = con.Categories.FirstOrDefault().Title,
            DateTime = geo.Date
        })
    ).ToList();
© www.soinside.com 2019 - 2024. All rights reserved.