Swift uses LINQ to manipulate arrays/collections (with Swift's LINQ extensions, and Workarounds)

Source: Internet
Author: User
Tags arrays min

One, What is LINQ

LINQ is the abbreviation for Language Integrated query (language integration queries). It is an important feature introduced by Microsoft in. NET 3.5. Since it was introduced by Microsoft, the corresponding programming is naturally the C # and Visual Basic languages.

The role of 1,LINQ

Let's use the same API (SQL-like syntax to query) to manipulate different data sources. For example, SQL Server, Oracle, XML, and data collections in memory, and of course developers can add more data sources using the extension framework that they provide.

Query operators for 2,LINQ

LINQ defines approximately 40 query operators, such as Select, from, in, where, and order by (C #). Use these operators to write query statements.

3,LINQ's Operation syntax

There are two types of syntax to choose for LINQ Queries: Query method Syntax (Fluent Syntax), and query expressions (queries Expression).
Query method: Mainly by using the extension method defined in the System.Linq.Enumerable class and lambda expression way to query.
Query statement: A query approach that is closer to SQL syntax and more readable.

Examples of the use of 4,linq

The following is an example of using a collection of data in the LINQ operation memory.
For example, we have a collection of contacts with the names, age, and telephone numbers of the three attributes. We just want to find people under the age of 40, and only the contact name and age can be returned in the result set (note that we don't need a phone here).
Then the combination of the WHERE statement and the SELECT statement is available, and the corresponding C # code is as follows (for example, in Query method syntax):

var user1 = new User () {name = "John", age =, phone = "123456"};
var user2 = new User () {name = "Dick", age = ten, phone = "101"};
var user3 = new User () {name = "Harry", age =, phone = "110"};
list<user> usercollection = new list<user> () {user1, user2, user3};

var results = Usercollection
. Where (c => c.age < 40)
. Select (c => new {c.name, c.age});

foreach (var result in results)
Console.WriteLine (Result. ToString ());
Console.ReadLine ();

Second, Swift's support for LINQ

Although LINQ is simple, efficient, and powerful, it is. NET, so you cannot use LINQ queries in Swift. The good news is that we can use map, filter, and reduce to implement similar functions with closure loops.

1, or the above contact example, in Swift to achieve the same function can be so written:

Let usercollection = [
(Name: "John", Age:34, Phone: "123456"),
(Name: "Dick", Age:10, Phone: "101"),
(Name: "Harry", age:45, Phone: "110")]

Let results = Usercollection.lazy
. filter {C in c.age < 45}
. map {($0.name, $0.age)}

For results {
Print (Result)

2, more examples

You can view an item on GitHub: LINQ Samples in Swift 2.0
It provides more than 100 examples of how various LINQ queries are replaced in Swift, which you can look at.

Third, add a LINQ extension to Swift

Sometimes simply using map, filter, and reduce is not enough to meet our needs, but the great God on the Internet provides the relevant tripartite library, so that we can easily use LINQ in Swift. The following describes the personal feel better extension library: Sinq.

1,SINQ Introduction

As the name suggests, SINQ is the abbreviation for swift integrated Query, and of course we can call it LINQ for Swift.
Sinq is similar to the LINQ Query method syntax (Fluent Syntax), which provides a number of query methods, such as Aggregate/reduce, all, any, concat, contains, count, distinct, Each, elementat, except, A, groupBy, GroupJoin, intersect, join, last, Min/max, Argmin/argmax, by, reverse, Selec T map, SelectMany, single, Skip, Take, thenby/thenbydescending, ToArray, todictionary/tolookupdictionary, Union, Wheretrue/filter, zip

Installation configuration for 2,SINQ

GitHub Address: Https://github.com/slazyk/SINQ
After downloading, add the Sinq.swift to the project.

Examples of the use of 3,sinq

(1) Wheretrue and select method

or to achieve the same function above, find people under the age of 40 years old, and return the result set only need contact name and age.

Let usercollection = [
(Name: "John", Age:34, Phone: "123456"),
(Name: "Dick", Age:10, Phone: "101"),
(Name: "Harry", age:45, Phone: "110")]

Let results = Sinq (usercollection)
. wheretrue{$0.age < 40}
. select{($0.name, $0.age)}

For results {
Print (Result)

(2) Orderby/orderbydescending sorting method

Identify persons under 40 years of age, and arrange them in ascending order by age.

Let results = Sinq (usercollection)
. wheretrue{$0.age < 40}
. orderby{$0.age}

(3) Min/max Minimum Maximum value method

Check the minimum age for all contacts.

Let result = Sinq (usercollection). min{$0.age}
Print (Result)//10

(4) Argmin/argmax Gets the element object containing the minimum maximum value

Check out the minimum age of the contact person.

Let result = Sinq (usercollection). argmin{$0.age}
Print (Result)//("Dick", 10, "101")

(5) Skip skips a fixed number of elements, take gets a fixed number of elements

The 2nd and 3rd contacts are queried.

Let results = Sinq (usercollection). Skip (1). Take (2)

For results {
Print (Result)
("Dick", 10, "101")
("Harry", 45, "110")

(6) All to determine whether all elements meet the conditions

Determine whether all contacts are younger than 40 years of age.

Let result = Sinq (usercollection). all{$0.age < 40}
Print (Result)//false

(7) Any to determine whether there is a meeting condition element

Determine if the contact has an age of less than 40 years.

Let result = Sinq (usercollection). any{$0.age < 40}
Print (Result)//true

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.