• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

mythz/kotlin-linq-examples: C#'s 101 LINQ Samples translated to Kotlin

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称(OpenSource Name):

mythz/kotlin-linq-examples

开源软件地址(OpenSource Url):

https://github.com/mythz/kotlin-linq-examples

开源编程语言(OpenSource Language):

Kotlin 100.0%

开源软件介绍(OpenSource Introduction):

101 C# LINQ Samples in Kotlin

This project contains the C# 101 LINQ Samples rewritten to Kotlin. Like the existing Java LINQ Examples, Kotlin examples run and have their results displayed inside an Android App courtesy of the rich support for Kotlin in Android Studio.

Compare Kotlin to other LINQ examples written in:

Comparing against Java examples showcases the power and expressiveness of both languages ability for developing native Android Apps where Java 7 is by far the worst language for functional/LINQ-style programming vs Kotlin which is one of the best - resulting in a much more readable and maintainable code-base that's less than 1/2 the size.

Kotlin Android Resources

To help getting started with Kotlin, we'll maintain links to useful resources helping to develop Android Apps with Kotlin below:

Call .NET Web Services from Kotlin

If you're looking to create an effortles typed API for consuming .NET Web Services in JVM or Kotlin Android Apps checkout ServiceStack's Kotlin Add ServiceStack Reference.

Running the examples

Each of the LINQ Examples can be run from the included Android App with its results logged to the screen:

Run the included Android Studio project to execute all the examples. You can also choose to only run specific examples by commenting out any of the sections you're not interested in MainActivity.kt.

A copy of the LINQ examples output is also available in linq-log.txt.

Contents

The samples below mirrors the C# LINQ samples layout with the names of the top-level Java methods matching their corresponding C# examples.

LINQ - Restriction Operators / MSDN C#

LINQ - Projection Operators / MSDN C#

LINQ - Partitioning Operators / MSDN C#

LINQ - Ordering Operators / MSDN C#

LINQ - Grouping Operators / MSDN C#

LINQ - Set Operators / MSDN C#

LINQ - Conversion Operators / MSDN C#

LINQ - Element Operators / MSDN C#

LINQ - Generation Operators / MSDN C#

LINQ - Quantifiers / MSDN C#

LINQ - Aggregate Operators / MSDN C#

LINQ - Miscellaneous Operators / MSDN C#

LINQ - Query Execution / MSDN C#

LINQ - Join Operators / MSDN C#

Kotlin Functional Utils

Kotlin has great language and built-in library support to simplify programming in a functional-style where most of the LINQ examples are able to use Kotlins built-in utils. Some of the more advanced LINQ examples like JOIN's were missing in Kotlins standard library, for this we leverage the existing implementations in ServiceStack's Java and Android Client Library: net.servicestack:android.

Install

To include it in your Android Studio project, add it to your build.gradle dependency, e.g:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'net.servicestack:android:1.0.31'
}

Pure Java projects should add the net.servicestack:client dependency instead:

dependencies {
    compile 'net.servicestack:client:1.0.31'
}

Alternatively this library is also automatically added when Adding a Typed Remote Service Reference with ServiceStack IDE Plugins for Intellij IDEA and Eclipse Maven projects.

Kotlin Extensions

Only a 2 extensions were required to cover Kotlin's missing difference API.

Side-by-side - C# LINQ vs Kotlin

For a side-by-side comparison, the original C# source code is displayed above the equivalent Kotlin translation.

  • The Output shows the logging output of running the Kotlin Android App.
  • Outputs ending with ... illustrates only a partial response is displayed.
  • The C# ObjectDumper util used is downloadable from MSDN - ObjectDumper.zip

LINQ - Restriction Operators

linq1: Where - Simple 1

//c#
public void Linq1() 
{ 
    int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 
  
    var lowNums = 
        from n in numbers 
        where n < 5 
        select n; 
  
    Console.WriteLine("Numbers < 5:"); 
    foreach (var x in lowNums) 
    { 
        Console.WriteLine(x); 
    } 
}  
//kotlin
fun linq1() {
    val numbers = intArrayOf(5, 4, 1, 3, 9, 8, 6, 7, 2, 0)

    val lowNums = numbers.filter { it < 5 }

    Log.d("Numbers < 5:")
    lowNums.forEach { Log.d(it) }
}

Output

Numbers < 5:
4
1
3
2
0

linq2: Where - Simple 2

//c#
public void Linq2() 
{ 
    List<Product> products = GetProductList(); 
  
    var soldOutProducts = 
        from p in products 
        where p.UnitsInStock == 0 
        select p; 
  
    Console.WriteLine("Sold out products:"); 
    foreach (var product in soldOutProducts) 
    { 
        Console.WriteLine("{0} is sold out!", product.ProductName); 
    } 
} 
//kotlin
fun linq2() {
    val soldOutProducts = products.filter { it.unitsInStock == 0 }

    Log.d("Sold out products:")
    soldOutProducts.forEach { Log.d("${it.productName} is sold out!") }
}

Output

Sold out products:
Chef Anton's Gumbo Mix is sold out!
Alice Mutton is sold out!
Thüringer Rostbratwurst is sold out!
Gorgonzola Telino is sold out!
Perth Pasties is sold out!

linq3: Where - Simple 3

//c#
public void Linq3() 
{ 
    List<Product> products = GetProductList(); 
  
    var expensiveInStockProducts = 
        from p in products 
        where p.UnitsInStock > 0 && p.UnitPrice > 3.00M 
        select p; 
  
    Console.WriteLine("In-stock products that cost more than 3.00:"); 
    foreach (var product in expensiveInStockProducts) 
    { 
        Console.WriteLine("{0} is in stock and costs more than 3.00.", product.ProductName); 
    } 
} 
//kotlin
fun linq3() {
    val expensiveInStockProducts = products.filter { it.unitsInStock > 0 && it.unitPrice > 3.00 }

    Log.d("In-stock products that cost more than 3.00:")
    expensiveInStockProducts.forEach { Log.d("${it.productName} is in stock and costs more than 3.00.") }
}

Output

In-stock products that cost more than 3.00:
Chai is in stock and costs more than 3.00.
Chang is in stock and costs more than 3.00.
Aniseed Syrup is in stock and costs more than 3.00.
...

linq4: Where - Drilldown

//c#
public void Linq4() 
{ 
    List<Customer> customers = GetCustomerList(); 
  
    var waCustomers = 
        from c in customers 
        where c.Region == "WA" 
        select c; 
  
    Console.WriteLine("Customers from Washington and their orders:"); 
    foreach (var customer in waCustomers) 
    { 
        Console.WriteLine("Customer {0}: {1}", customer.CustomerID, customer.CompanyName); 
        foreach (var order in customer.Orders) 
        { 
            Console.WriteLine("  Order {0}: {1}", order.OrderID, order.OrderDate); 
        } 
    } 
} 
//kotlin
fun linq4() {
    val waCustomers = customers.filter { "WA" == it.region }

    Log.d("Customers from Washington and their orders:")
    waCustomers.forEach { c ->
        Log.d("Customer ${c.customerId} ${c.companyName}")
        c.orders.forEach { Log.d("  Order ${it.orderId}: ${dateFmt(it.orderDate)}") }
    }
}

Output

Customers from Washington and their orders:
Customer LAZYK Lazy K Kountry Store
  Order 10482: 1997/03/21
  Order 10545: 1997/05/22
Customer TRAIH Trail's Head Gourmet Provisioners
  Order 10574: 1997/06/19
  Order 10577: 1997/06/23
  Order 10822: 1998/01/08
  ...

linq5: Where - Indexed

//c#
public void Linq5() 
{ 
    string[] digits = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" }; 
  
    var shortDigits = digits.Where((digit, index) => digit.Length < index); 
  
    Console.WriteLine("Short digits:"); 
    foreach (var d in shortDigits) 
    { 
        Console.WriteLine("The word {0} is shorter than its value.", d); 
    } 
}
//kotlin
fun linq5() {
    val digits = arrayOf("zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine")

    val shortDigits = digits.filterIndexed { i, it -> it.length < i }

    Log.d("Short digits:")
    shortDigits.forEach { Log.d("The word $it is shorter than its value.") }
}

Output

Short digits:
The word five is shorter than its value.
The word six is shorter than its value.
The word seven is shorter than its value.
The word eight is shorter than its value.
The word nine is shorter than its value.

LINQ - Projection Operators

linq6: Select - Simple 1

//c#
public void Linq6() 
{ 
    int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; 
  
    var numsPlusOne = 
        from n in numbers 
        select n + 1; 
  
    Console.WriteLine("Numbers + 1:"); 
    foreach (var i in numsPlusOne) 
    { 
        Console.WriteLine(i); 
    } 
}
//kotlin
fun linq06() {
    val numbers = intArrayOf(5, 4, 1, 3, 9, 8, 6, 7, 2, 0)

    val numsPlusOne = numbers.map { it + 1 }

    Log.d("Numbers + 1:")
    numsPlusOne.forEach { Log.d(it) }
}

Output

Numbers + 1:
6
5
2
4
10
9
7
8
3
1

linq7: Select - Simple 2

//c#
public void Linq7() 
{ 
    List<Product> products = GetProductList(); 
  
    var productNames = 
        from p in products 
        select p.ProductName; 
  
    Console.WriteLine("Product Names:"); 
    foreach (var productName in productNames) 
    { 
        Console.WriteLine(productName); 
    } 
}
//kotlin
fun linq07() {
    val productNames = products.map { it.productName }

    Log.d("Product Names:")
    productNames.forEach { Log.d(it) }
}

Output

Product Names:
Chai
Chang
Aniseed Syrup
Chef Anton's Cajun Seasoning
Chef Anton's Gumbo Mix
...

上一篇:
nokyotsu/ezthesis: Formato de tesis para LaTeX发布时间:2022-07-09
下一篇:
benasher44/uuid: Kotlin Multiplatform UUID发布时间:2022-07-07
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap