Scala 中的 LINQ 类似物?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3785413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
LINQ analogues in Scala?
提问by J?rg W Mittag
Are there any sane analogues to LINQ (.NET) exists for Scala?
Scala 是否存在与 LINQ (.NET) 类似的东西?
回答by J?rg W Mittag
It depends on what exactly you mean by "LINQ". LINQ is many things.
这取决于“LINQ”的确切含义。LINQ 有很多东西。
The most obvious answer would be: just use the .NET port of Scala. It gives you full native access to everything in .NET, which obviously includes LINQ.
最明显的答案是:只使用 Scala 的 .NET 端口。它使您可以完全本地访问 .NET 中的所有内容,其中显然包括 LINQ。
Unfortunately, the .NET port of Scala was dropped a couple of years ago. Fortunately, it was picked up again a couple of months ago, with official funding directly from Microsoft no less. You can expect a release sometime in the 2011/2012 timeframe.
不幸的是,Scala 的 .NET 端口在几年前被删除了。幸运的是,它在几个月前再次被采用,官方资金也直接来自微软。您可以期待在 2011/2012 时间范围内的某个时间发布。
Anyway, what is LINQ?
无论如何,什么是 LINQ?
A couple of features where added to .NET and specifically C# and VB.NET forLINQ. They are not technically part of LINQ, but are necessary prerequisites: type inference, anonymous (structural) types, lambda expressions, function types (Func<T...>and Action<T...>) and expression trees. All of these have been in Scala for a long time, most have been there forever.
一些功能添加到 .NET 中,特别是用于LINQ 的C# 和 VB.NET 。从技术上讲,它们不是 LINQ 的一部分,但它们是必要的先决条件:类型推断、匿名(结构)类型、lambda 表达式、函数类型(Func<T...>和Action<T...>)和表达式树。所有这些都在 Scala 中存在了很长时间,大多数已经永远存在了。
Also not directly part of LINQ, but in C#, LINQ query expressions can be used to generate XML, to emulate VB.NET's XML literals. Scala has XML literals, like VB.NET.
也不直接是 LINQ 的一部分,但在 C# 中,LINQ 查询表达式可用于生成 XML,以模拟 VB.NET 的 XML 文字。Scala 有 XML 文本,如 VB.NET。
More specifically, LINQ is
更具体地说,LINQ是
- a specification for a set of standard query operators
- a set of implementations for those operators (i.e.
IQueryable, LINQ-to-XML, LINQ-to-SQL, LINQ-to-Objects) - a built-in embedded syntax for LINQ query comprehensions
- a monad
- 一组标准查询运算符的规范
- 这些运算符的一组实现(即
IQueryableLINQ-to-XML、LINQ-to-SQL、LINQ-to-Objects) - 用于 LINQ 查询理解的内置嵌入式语法
- 单子
In Scala, like in pretty much any other functional language (and in fact also pretty much any other object-oriented language, too), the query operators are simply part of the standard collections API. In .NET, they have a little bit weird names, whereas in Scala, they have the same standard names they have in other languages: Selectis map, Aggregateis reduce(or fold), SelectManyis flatMap, Whereis filteror withFilter, orderByis sortor sortByor sortWith, and there are zip, takeand takeWhileand so on. So, that takes care of both the specification and the LINQ-to-Objects implementation. Scala's XML libraries also implement the collections APIs, which takes care of LINQ-to-XML.
在 Scala 中,就像在几乎任何其他函数式语言中一样(实际上也几乎在任何其他面向对象语言中),查询运算符只是标准集合 API 的一部分。在.NET中,他们有一点点怪异的名字,而在Scala中,它们具有相同的标准名称,他们在其他语言版本:Select是map,Aggregate是reduce(或fold),SelectMany是flatMap,Where是filter或withFilter,orderBy是sort或sortBy或sortWith,并且有zip,take并且takeWhile和很快。因此,这需要处理规范和 LINQ-to-Objects 实现。Scala 的 XML 库还实现了集合 API,它负责处理 LINQ-to-XML。
SQL APIs are not built into Scala, but there are third-party APIs which implement the collection API.
SQL API 没有内置到 Scala 中,但有第三方 API 实现了集合 API。
Scala also has specialized syntax for those APIs, but unlike Haskell, which tries to make them look like imperative C blocks and C#, which tries to make them look like SQL queries, Scala tries to make them look like forloops. They are called forcomprehensionsand are the equivalent to C#'s query comprehensions and Haskell's monad comprehensions. (They also replace C#'s foreachand generators (yield return)).
Scala 对这些 API 也有专门的语法,但与 Haskell 试图使它们看起来像命令式 C 块和 C#(试图使它们看起来像 SQL 查询)不同,Scala 试图使它们看起来像for循环。它们被称为for推导式,相当于 C# 的查询推导式和 Haskell 的 monad 推导式。(它们还取代了 C#foreach和生成器 ( yield return))。
But if you reallywant to know whether or not there are analogues for LINQ in Scala, you will first have to specificy what exactly you mean by "LINQ". (And of course, if you want to know whether they are "sane", you will have to define that, too.)
但是如果你真的想知道 Scala 中是否有 LINQ 的类似物,你首先必须明确你所说的“LINQ”到底是什么意思。(当然,如果你想知道他们是否“理智”,你也必须定义它。)
回答by onof
All LINQ IEnumerableextensions are available in Scala. For example:
所有 LINQIEnumerable扩展都在 Scala 中可用。例如:
Linq:
林克:
var total = orders
.Where(o => o.Customer == "myCustomer")
.SelectMany(o => o.OrderItems)
.Aggregate(0, (sum, current) => sum + current.Price * current.Count);
scala:
斯卡拉:
val total = orders
.filter(o => o.customer == "myCustomer")
.flatMap(o => o.orderItems)
.foldLeft(0)((s, c) => s + c.price * c.count)
回答by Miuler
Slick
圆滑的
is a modern database query and access library for Scala. (http://slick.typesafe.com/)
是 Scala 的现代数据库查询和访问库。( http://slick.typesafe.com/)
@table("COFFEES") case class Coffee(
@column("COF_NAME") name: String,
@column("SUP_ID") supID: Int,
@column("PRICE") price: Double
)
val coffees = Queryable[Coffee]
// for inserts use lifted embedding or SQL
val l = for {
c <- coffees if c.supID == 101
// ^ comparing Int to Int!
} yield (c.name, c.price)
backend.result( l, session )
.foreach { case (n, p) => println(n + ": " + p) }
回答by Ben James
There are many situations in Scala where you can use monadic constructs as a sort of query language.
在 Scala 中有很多情况,您可以将 monadic 构造用作一种查询语言。
For example, to query XML (in this case, extracting URLs from links in some XHTML):
例如,要查询 XML(在这种情况下,从某些 XHTML 中的链接中提取 URL):
def findURLs(xml: NodeSeq): Seq[URL] =
for {
a <- xml \ "a"
href <- a attribute "href"
url <- href.text
} yield URL(url)
For an analogue of LINQ to SQL, the closest thing is probably ScalaQuery. To lift an example right out of the docs:
对于 LINQ to SQL 的类比,最接近的可能是ScalaQuery。从文档中举出一个例子:
val q4c = for {
u <- Users
o <- Orders if o.userID is u.id
} yield u.first ~ o.orderID

