在Scala中将映射序列转换为键映射到值序列

时间:2018-08-21 08:18:56

标签: scala transformation

我正在尝试绘制一系列地图,例如

var x = dbContext.Junctions                              // from all junctions
    .Where(junction => junction.ProductId == productId)  // take only the ones with productId

                                                          // The first join:
    .Join(dbContext.Parts,                                // Join with Parts
        junction => junction.PartId,                      // from the Junction take the PartId,
        part => part.Id,                                  // from the Parts take the Id
        (junction, part) => new                           // when they match make one new object
        {                                                 // containing some properties
            EnumerationId = junction.EnumId,
            PartNumber = part.Number,
            PartDescription = part.Description,
        })

                                                          // Second Join
        .Join(dbContext.Enumerations,                     // Join with enumerations
            junction => junction.EnumerationId,           // from the 1st join result take EnumerationId
            enumeration => enumeration.Id,                // from enumerations take Id
            (junction, enumeration) => new                // when they match make one new object
            {                                             // containing your desired properties
                EnumerationCode = enumeration.Code,
                PartNumber = junction.PartNumber,
                PartDescription = junction.PartDescription,
            });

从这些映射中的键到它们在原始序列中跨每个映射映射的值序列进入映射。

因此上述内容应转化为

var result = dbContext.Junctions
    .Where(junction => junction.ProductId == productId)
    .Select(junction => new
    {
        Description = junction.Product.Description,
        EnumerationCode = junction.Enumeration.EnumerationCode,
        PartNumber = junction.Part.Number,
        PartDescription = junction.Part.Description,
    });

我可以想到一些解决方法,但是我正在寻找一种惯用的解决方案或最佳的Scala样式进行此类转换?理想情况下,不会造成真正的浪费,但性能并不是一个大问题。

谢谢!

1 个答案:

答案 0 :(得分:3)

您可以这样做:

val output = input.flatten.groupBy(_._1).mapValues(_.map(_._2))

它将首先将地图拼合为所有地图条目的Seq。然后,将地图项按其键分组。最后,将值(现在是映射条目列表)映射到映射值列表。