[英]Scala shortest equivalent to c# LINQ
I need to create a bunch of new objects in scala What is the shortest equivalent for the following C# code? 我需要在scala中创建一堆新对象以下C#代码的最短等价物是什么?
var n = 100;
var persons = Enumerable.Range(1, n).Select(x=>new Person(x)).ToList();
and whats wrong with this? 这有什么不对吗?
val persons: List[Person] = (1 to n) map (new Person(_))
Use List.range : 使用List.range :
List.range(1, n + 1).map(new Person(_))
Or as Lee suggested: 或者李建议:
(1 to n).map(new Person(_)).toList
Calling toList
is required because (1 to n).map(new Person(_))
produces an IndexedSeq[Person]
. 调用toList
是必需的,因为(1 to n).map(new Person(_))
生成一个IndexedSeq[Person]
。 Note also that the type of 1 to n
is Range.Inclusive
and that it is different to the type of List.range(1, n + 1)
which is List[Int]
. 另请注意, 1 to n
的类型是Range.Inclusive
,它与List.range(1, n + 1)
的类型不同,它是List[Int]
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.