下面的示例展示了 X# 中的几个 LINQ 查询:
//references:
//System.dll
//System.Core.dll
//System.Linq.dll
USING System.Collections.Generic
USING System.Linq
USING STATIC System.Console
FUNCTION Start AS VOID
VAR oDev := GetDevelopers()
VAR oC := GetCountries()
VAR oAll := FROM D IN oDev ;
JOIN C IN oC ON D:Country EQUALS C:Name ;
ORDERBY D:LastName ;
SELECT CLASS {D:Name, D:Country, C:Region} // 匿名类!
// oAll 的类型为 IOrderedEnumerable<<>f__AnonymousType0<Developer,Country>>
// 我们更倾向于使用 VAR 关键字!
VAR oGreek := FROM Developer IN oDev ;
WHERE Developer:Country == "Greece" ;
ORDERBY Developer:LastName DESCENDING ;
SELECT Developer
// oGreek 的类型为 IOrderedEnumerable<Developer>
// 我们更倾向于使用 VAR 关键字!
VAR oCount := FROM Developer IN oDev ;
GROUP Developer BY Developer:Country INTO NewGroup ;
ORDERBY NewGroup:Key SELECT NewGroup
// oCount 的类型为 IOrderedEnumerable<<IGrouping<string,Developer>>
// 我们更倾向于使用 VAR 关键字!
WriteLine(e"X# does LINQ!\n")
WriteLine(e"All X# developers (country+lastname order)\n")
FOREACH VAR oDeveloper IN oAll
WriteLine("{0} in {1}, {2}",oDeveloper:Name, oDeveloper:Country, oDeveloper:Region)
NEXT
WriteLine(e"\nGreek X# Developers (descending lastname)\n")
FOREACH oDeveloper AS Developer IN oGreek
WriteLine(oDeveloper:Name)
NEXT
WriteLine(e"\nDevelopers grouped per country\n")
FOREACH VAR country IN oCount
WriteLine(i"{country.Key}, {country.Count()} developer(s)")
FOREACH VAR oDeveloper IN country
WriteLine(" " + oDeveloper:Name)
NEXT
NEXT
WriteLine("Enter to continue")
ReadLine()
RETURN
FUNCTION GetDevelopers AS IList<Developer>
// 该函数对开发人员列表使用集合初始化程序,对开发人员对象使用对象初始化程序
VAR oList := List<Developer>{} { ;
Developer{}{ FirstName := "Chris", LastName := "Pyrgas", Country := "Greece"},;
Developer{}{ FirstName := "Robert", LastName := "van der Hulst", Country := "The Netherlands"},;
Developer{}{ FirstName := "Fabrice", LastName := "Foray", Country := "France"},;
Developer{}{ FirstName := "Nikos", LastName := "Kokkalis", Country := "Greece"} ;
}
RETURN oList
FUNCTION GetCountries AS IList<Country>
// 该函数使用集合初始化来处理县列表,并使用对象初始化来处理国家对象
VAR oList := List<Country>{}{ ;
Country{} {Name := "Greece", Region := "South East Europe"},;
Country{} {Name := "France", Region := "West Europe"},;
Country{} {Name := "The Netherlands", Region := "North West Europe"} ;
}
RETURN oList
CLASS Developer
PROPERTY Name AS STRING GET FirstName + " " + LastName
PROPERTY FirstName AS STRING AUTO
PROPERTY LastName AS STRING AUTO
PROPERTY Country AS STRING AUTO
END CLASS
CLASS Country
PROPERTY Name AS STRING AUTO
PROPERTY Region AS STRING AUTO
END CLASS