组对象共享相同的键并将它们转换为另一个对象

时间:2017-07-05 17:34:02

标签: c# .net linq

这些是我的课程:

class Schedule
{
    Int32 Id {get; set;}
    String CustomerName {get; set;}
    DateTime SchedStartDate {get; set;}
    DateTime SchedEndDate {get; set;}
    List<Body> Body {get; set;}
}

class Body
{
    Int32 Id {get; set;}
    String ProductBarcode {get; set;}
    Int32 ProductItemId {get; set;}
    DateTime DtEvaluation {get; set;}
    List<History> History {get; set;}
}

class History
{
    Int32 ActionId { get; set; }
    String Description { get; set; }
    String Picture { get; set; }
    String Observation { get; set; }
    Int32 EvalItemId { get; set; }
    Int32 EvalCriteriaId { get; set; }
}

我有一个Schedule对象,Body.ProductBarcode列表中会重复字符串Schedule.Body。此外,有时列表Body.History为空,有时则不是。

从应用程序的角度来看,Body.ProductBarcode重复是正确的,但是当我尝试合并数据时,它给我带来了一些麻烦,因为我希望将Schedule对象转换为另一个class(我觉得更容易使用):

class EmailSchedule
{
    String Id { get; set; }
    Int32 ProductId { get; set; }
    DateTime DtEvaluation { get; set; }
    List<EmailHistory> History { get; set; }
}
class EmailHistory
{
    Int32 ActionId { get; set; }
    String Description { get; set; }
    String Picture { get; set; }
    String Observation { get; set; }
    String EvalItemId { get; set; }
    Int32 EvalCriteriaId { get; set; }
}

请记住,此时,我唯一感兴趣的是Body.ProductBarcode密钥和每个Body.History列表。 Schedules的属性已经安全可靠,其他Body的属性也无用。

This is an example将转换为Schedule对象

的JSON

我的问题在于,由于重复Body.ProductBarcode我需要对Body.ProductBarcode匹配的匹配项进行分组,然后将所有Body.History列表放到同一个{{1}列表。

我尝试使用LINQ,但由于我不熟悉它,我无法使其正常工作。

2 个答案:

答案 0 :(得分:1)

我仍然不能100%确定你正在寻找什么样的结构,但你可以尝试一下,让我知道它是否接近你想要的地方吗?

根据您的反馈,我可以调整它。 (schd是你的日程安排对象)

var scheduleList = schd.Body.GroupBy(b => b.ProductBarcode).Select(b => b.Select(bod => new EmailSchedule
{
    Id = s.Id.ToString(),
    DtEvaluation = bod.DtEvaluation,
    ProductId = bod.ProductItemId,
    History = bod.History
})).SelectMany(b => b);      //flatten to single list

P.S。对于您的类,使用public会很好,否则它不会从json反序列化,并且因为EmailHistoryHistory类是相同的,所以我只使用History。如果您确实需要将其投放到EmailHistory,则需要将代码添加到行History = bod.History

答案 1 :(得分:1)

我假设您不关心任何EmailSchedule属性,因为除了Body之外,您说其他History属性都没用。您可以将其他History属性复制到EmailHistory,方法与我在此处完全相同。

以下是混合查询/方法语法:

var ans = from b in bodies
          group b by b.ProductBarcode into bg
          let bgf = bg.First()
          select new EmailSchedule {
              History = bg.SelectMany(b => b.History, (b, h) => new EmailHistory { ActionId = h.ActionId, Description = h.Description }).ToList()
          };

这是查询语法:

var ans = from b in bodies
          group b by b.ProductBarcode into bg
          let bgf = bg.First()
           select new EmailSchedule {
               History = (from b in bg from h in b.History select new EmailHistory { ActionId = h.ActionId, Description = h.Description }).ToList()
          };
相关问题