Scala在map()&中使用匿名对象的语法flatMap()

时间:2017-04-04 14:44:07

标签: scala

例如,我有以下Scala类(在C#,ofc中也是如此):

import com.github.nscala_time.time.Imports._

class Flight{
  var FlDate:DateTime = new DateTime
  var Origin = ""
  var Destination = ""
}

flight = Flight []

原创C#代码:

var rez = flights.SelectMany(p => new[] {
     new { Airport = p.Origin, IsOrigin = true },
     new { Airport = p.Destination, IsOrigin = false }
   })
   .GroupBy(x => x.Airport)
   .Select(g => new
   {
       Airport = g.Key,
       LeftCount = g.Count(x => x.IsOrigin),
       ArrivedCount = g.Count(x => !x.IsOrigin)
   });

Scala代码不正确:

var rez = flights
  .flatMap(case (airport, isOrigin) => {
  new { airport = _.origin, isOrigin = true }, // issue - ?
  new { airport = _.destination, isOrigin = false } // issue - ?
})
.groupBy(_.airport)
.map {
  case (airport, leftCount, arrivedCount) => new {
    val airport = ??? // issue - g.Key?
    val leftCount = ??? // issue - g.Count(x => x.IsOrigin) ?
    val arrivedCount = ??? // issue - g.Count(x => !x.IsOrigin) ?
  }
}

因此,正如您在代码中看到的那样,结果我需要一个具有以下属性的对象数组:ListBuffer[airport:String, leftCount :Int, arrivedCount:Int]

因此...

  1. 有人可以帮忙解决问题吗?
  2. 也许,有人知道一些关于“Scala中匿名对象的工作语法”主题的好文章吗?

1 个答案:

答案 0 :(得分:1)

你可以这样做:

errors= str(errors)
for d in errors[:]:
if 'False' in d:
    Ic.append(current_mA2)