linq

package module
v2.0.0-rc0+incompatible Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 11, 2016 License: Apache-2.0 Imports: 3 Imported by: 0

README

go-linq GoDoc Build Status Coverage Status Go Report Card

A powerful language integrated query (LINQ) library for Go.

  • Written in vanilla Go!
  • Safe for concurrent use
  • Complete lazy evaluation with iterator pattern
  • Supports arrays, slices, maps, strings, channels and custom collections (collection needs to implement Iterable interface and element - Comparable interface)

Installation

$ go get github.com/ahmetalpbalkan/go-linq

⚠ ⚠ go-linq has recently introduced breaking API changes with v2.0.0. See release notes for details. v2.0.0 comes with a refined interface, dramatically increased performance and memory efficiency, and new features such as lazy evaluation (read more).

The old version is still available in archive/0.9 branch and tagged as 0.9 as well. If you are using go-linq, please vendor a copy of it in your source tree to avoid getting broken by upstream changes.

Quickstart

Usage is as easy as chaining methods like:

From(slice) .Where(predicate) .Select(selector) .Union(data)

Example: Find all owners of cars manufactured from 2015

import . "github.com/ahmetalpbalkan/go-linq"
	
type Car struct {
    id, year int
    owner, model string
}

owners := []string{}

From(cars).Where(func(c interface{}) bool {
	return c.(Car).year >= 2015
}).Select(func(c interface{}) interface{} {
	return c.(Car).owner
}).ToSlice(&owners)

Example: Find the author who has written the most books

import . "github.com/ahmetalpbalkan/go-linq"
	
type Book struct {
	id      int
	title   string
	authors []string
}

author := From(books).SelectMany( // make a flat array of authors
	func(book interface{}) Query {
		return From(book.(Book).authors)
	}).GroupBy( // group by author
	func(author interface{}) interface{} {
		return author // author as key
	}, func(author interface{}) interface{} {
		return author // author as value
	}).OrderByDescending( // sort groups by its length
	func(group interface{}) interface{} {
		return len(group.(Group).Group)
	}).Select( // get authors out of groups
	func(group interface{}) interface{} {
		return group.(Group).Key
	}).First() // take the first author

Example: Implement a custom method that leaves only values greater than the specified threshold

type MyQuery Query

func (q MyQuery) GreaterThan(threshold int) Query {
	return Query{
		Iterate: func() Iterator {
			next := q.Iterate()

			return func() (item interface{}, ok bool) {
				for item, ok = next(); ok; item, ok = next() {
					if item.(int) > threshold {
						return
					}
				}

				return
			}
		},
	}
}

result := MyQuery(Range(1,10)).GreaterThan(5).Results()

More examples can be found in documentation.

Release Notes


v2.0.0 (2016-09-02)
* IMPORTANT: This release is a BREAKING CHANGE. The old version
  is archived at the 'archive/0.9' branch or the 0.9 tags.
* A COMPLETE REWRITE of go-linq with better performance and memory
  efficiency. (thanks @kalaninja!)
* API has significantly changed. Most notably:
  - linq.T removed in favor of interface{}
  - library methods no longer return errors 
  - PLINQ removed for now (see channels support)
  - support for channels, custom collections and comparables

v0.9-rc4
* GroupBy()

v0.9-rc3.2
* bugfix: All() iterating over values instead of indices

v0.9-rc3.1
* bugfix: modifying result slice affects subsequent query methods

v0.9-rc3
* removed FirstOrNil, LastOrNil, ElementAtOrNil methods 

v0.9-rc2.5
* slice-accepting methods accept slices of any type with reflections

v0.9-rc2
* parallel linq (plinq) implemented
* Queryable separated into Query & ParallelQuery
* fixed early termination for All

v0.9-rc1
* many linq methods are implemented
* methods have error handling support
* type assertion limitations are unresolved
* travis-ci.org build integrated
* open sourced on github, master & dev branches

Documentation

Overview

Package linq provides methods for querying and manipulating slices, arrays, maps, strings, channels and collections.

Authors: Alexander Kalankhodzhaev (kalan), Ahmet Alp Balkan

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Comparable

type Comparable interface {
	CompareTo(Comparable) int
}

Comparable is an interface that has to be implemented by a custom collection elememts in order to work with linq.

Example:

func (f foo) CompareTo(c Comparable) int {
	a, b := f.f1, c.(foo).f1

	if a < b {
		return -1
	} else if a > b {
		return 1
	}

	return 0
}

type Group

type Group struct {
	Key   interface{}
	Group []interface{}
}

Group is a type that is used to store the result of GroupBy method.

type Iterable

type Iterable interface {
	Iterate() Iterator
}

Iterable is an interface that has to be implemented by a custom collection in order to work with linq.

type Iterator

type Iterator func() (item interface{}, ok bool)

Iterator is an alias for function to iterate over data.

type KeyValue

type KeyValue struct {
	Key   interface{}
	Value interface{}
}

KeyValue is a type that is used to iterate over a map (if query is created from a map). This type is also used by ToMap() method to output result of a query into a map.

Example
m := make(map[int]bool)
m[10] = true

fmt.Println(From(m).Results())
Output:

[{10 true}]
Example (Second)
input := []KeyValue{
	{10, true},
}

m := make(map[int]bool)
From(input).ToMap(&m)
fmt.Println(m)
Output:

map[10:true]

type OrderedQuery

type OrderedQuery struct {
	Query
	// contains filtered or unexported fields
}

OrderedQuery is the type returned from OrderBy, OrderByDescending ThenBy and ThenByDescending functions.

func (OrderedQuery) Distinct

func (oq OrderedQuery) Distinct() OrderedQuery

Distinct method returns distinct elements from a collection. The result is an ordered collection that contains no duplicate values.

NOTE: Distinct method on OrderedQuery type has better performance than Distinct method on Query type

func (OrderedQuery) ThenBy

func (oq OrderedQuery) ThenBy(
	selector func(interface{}) interface{}) OrderedQuery

ThenBy performs a subsequent ordering of the elements in a collection in ascending order. This method enables you to specify multiple sort criteria by applying any number of ThenBy or ThenByDescending methods.

func (OrderedQuery) ThenByDescending

func (oq OrderedQuery) ThenByDescending(
	selector func(interface{}) interface{}) OrderedQuery

ThenByDescending performs a subsequent ordering of the elements in a collection in descending order. This method enables you to specify multiple sort criteria by applying any number of ThenBy or ThenByDescending methods.

type Query

type Query struct {
	Iterate func() Iterator
}

Query is the type returned from query functions. It can be iterated manually as shown in the example.

Example
query := From([]int{1, 2, 3, 4, 5}).Where(func(i interface{}) bool {
	return i.(int) <= 3
})

next := query.Iterate()
for item, ok := next(); ok; item, ok = next() {
	fmt.Println(item)
}
Output:

1
2
3

func From

func From(source interface{}) Query

From initializes a linq query with passed slice, array or map as the source. String, channel or struct implementing Iterable interface can be used as an input. In this case From delegates it to FromString, FromChannel and FromIterable internally.

func FromChannel

func FromChannel(source <-chan interface{}) Query

FromChannel initializes a linq query with passed channel, linq iterates over channel until it is closed.

func FromIterable

func FromIterable(source Iterable) Query

FromIterable initializes a linq query with custom collection passed. This collection has to implement Iterable interface, linq iterates over items, that has to implement Comparable interface or be basic types.

func FromString

func FromString(source string) Query

FromString initializes a linq query with passed string, linq iterates over runes of string.

func Range

func Range(start, count int) Query

Range generates a sequence of integral numbers within a specified range.

func Repeat

func Repeat(value interface{}, count int) Query

Repeat generates a sequence that contains one repeated value.

func (Query) Aggregate

func (q Query) Aggregate(
	f func(interface{}, interface{}) interface{}) interface{}

Aggregate applies an accumulator function over a sequence.

Aggregate method makes it simple to perform a calculation over a sequence of values. This method works by calling f() one time for each element in source except the first one. Each time f() is called, Aggregate passes both the element from the sequence and an aggregated value (as the first argument to f()). The first element of source is used as the initial aggregate value. The result of f() replaces the previous aggregated value.

Aggregate returns the final result of f().

Example
input := []string{"apple", "mango", "orange", "passionfruit", "grape"}

result := From(input).Aggregate(func(r interface{}, i interface{}) interface{} {
	if len(r.(string)) > len(i.(string)) {
		return r
	}
	return i
})

fmt.Println(result)
Output:

passionfruit

func (Query) AggregateWithSeed

func (q Query) AggregateWithSeed(
	seed interface{},
	f func(interface{}, interface{}) interface{},
) interface{}

AggregateWithSeed applies an accumulator function over a sequence. The specified seed value is used as the initial accumulator value.

Aggregate method makes it simple to perform a calculation over a sequence of values. This method works by calling f() one time for each element in source except the first one. Each time f() is called, Aggregate passes both the element from the sequence and an aggregated value (as the first argument to f()). The value of the seed parameter is used as the initial aggregate value. The result of f() replaces the previous aggregated value.

Aggregate returns the final result of f().

func (Query) All

func (q Query) All(predicate func(interface{}) bool) bool

All determines whether all elements of a collection satisfy a condition.

func (Query) Any

func (q Query) Any() bool

Any determines whether any element of a collection exists.

func (Query) AnyWith

func (q Query) AnyWith(predicate func(interface{}) bool) bool

AnyWith determines whether any element of a collection satisfies a condition.

func (Query) Append

func (q Query) Append(item interface{}) Query

Append inserts an item to the end of a collection, so it becomes the last item.

func (Query) Average

func (q Query) Average() (r float64)

Average computes the average of a collection of numeric values.

func (Query) Concat

func (q Query) Concat(q2 Query) Query

Concat concatenates two collections.

The Concat method differs from the Union method because the Concat method returns all the original elements in the input sequences. The Union method returns only unique elements.

Example
q := From([]int{1, 2, 3}).Concat(From([]int{4, 5, 6}))
fmt.Println(q.Results())
Output:

[1 2 3 4 5 6]

func (Query) Contains

func (q Query) Contains(value interface{}) bool

Contains determines whether a collection contains a specified element.

func (Query) Count

func (q Query) Count() (r int)

Count returns the number of elements in a collection.

func (Query) CountWith

func (q Query) CountWith(predicate func(interface{}) bool) (r int)

CountWith returns a number that represents how many elements in the specified collection satisfy a condition.

func (Query) Distinct

func (q Query) Distinct() Query

Distinct method returns distinct elements from a collection. The result is an unordered collection that contains no duplicate values.

func (Query) DistinctBy

func (q Query) DistinctBy(selector func(interface{}) interface{}) Query

DistinctBy method returns distinct elements from a collection. This method executes selector function for each element to determine a value to compare. The result is an unordered collection that contains no duplicate values.

func (Query) Except

func (q Query) Except(q2 Query) Query

Except produces the set difference of two sequences. The set difference is the members of the first sequence that don't appear in the second sequence.

func (Query) ExceptBy

func (q Query) ExceptBy(
	q2 Query, selector func(interface{}) interface{}) Query

ExceptBy invokes a transform function on each element of a collection and produces the set difference of two sequences. The set difference is the members of the first sequence that don't appear in the second sequence.

func (Query) First

func (q Query) First() interface{}

First returns the first element of a collection.

func (Query) FirstWith

func (q Query) FirstWith(predicate func(interface{}) bool) interface{}

FirstWith returns the first element of a collection that satisfies a specified condition.

func (Query) GroupBy

func (q Query) GroupBy(
	keySelector func(interface{}) interface{},
	elementSelector func(interface{}) interface{},
) Query

GroupBy method groups the elements of a collection according to a specified key selector function and projects the elements for each group by using a specified function.

Example
input := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}

q := From(input).GroupBy(
	func(i interface{}) interface{} { return i.(int) % 2 },
	func(i interface{}) interface{} { return i.(int) })

fmt.Println(q.OrderBy(func(i interface{}) interface{} {
	return i.(Group).Key
}).Results())
Output:

[{0 [2 4 6 8]} {1 [1 3 5 7 9]}]

func (Query) GroupJoin

func (q Query) GroupJoin(
	inner Query,
	outerKeySelector func(interface{}) interface{},
	innerKeySelector func(interface{}) interface{},
	resultSelector func(outer interface{}, inners []interface{}) interface{},
) Query

GroupJoin correlates the elements of two collections based on key equality, and groups the results.

This method produces hierarchical results, which means that elements from outer query are paired with collections of matching elements from inner. GroupJoin enables you to base your results on a whole set of matches for each element of outer query.

The resultSelector function is called only one time for each outer element together with a collection of all the inner elements that match the outer element. This differs from the Join method, in which the result selector function is invoked on pairs that contain one element from outer and one element from inner.

GroupJoin preserves the order of the elements of outer, and for each element of outer, the order of the matching elements from inner.

Example
fruits := []string{
	"apple",
	"banana",
	"apricot",
	"cherry",
	"clementine",
}

q := FromString("abc").GroupJoin(
	From(fruits),
	func(i interface{}) interface{} { return i },
	func(i interface{}) interface{} { return []rune(i.(string))[0] },
	func(outer interface{}, inners []interface{}) interface{} {
		return KeyValue{string(outer.(rune)), inners}
	})

fmt.Println(q.Results())
Output:

[{a [apple apricot]} {b [banana]} {c [cherry clementine]}]

func (Query) Intersect

func (q Query) Intersect(q2 Query) Query

Intersect produces the set intersection of the source collection and the provided input collection. The intersection of two sets A and B is defined as the set that contains all the elements of A that also appear in B, but no other elements.

func (Query) IntersectBy

func (q Query) IntersectBy(
	q2 Query,
	selector func(interface{}) interface{},
) Query

IntersectBy produces the set intersection of the source collection and the provided input collection. The intersection of two sets A and B is defined as the set that contains all the elements of A that also appear in B, but no other elements.

IntersectBy invokes a transform function on each element of both collections.

func (Query) Join

func (q Query) Join(
	inner Query,
	outerKeySelector func(interface{}) interface{},
	innerKeySelector func(interface{}) interface{},
	resultSelector func(outer interface{}, inner interface{}) interface{},
) Query

Join correlates the elements of two collection based on matching keys.

A join refers to the operation of correlating the elements of two sources of information based on a common key. Join brings the two information sources and the keys by which they are matched together in one method call. This differs from the use of SelectMany, which requires more than one method call to perform the same operation.

Join preserves the order of the elements of outer collection, and for each of these elements, the order of the matching elements of inner.

Example
fruits := []string{
	"apple",
	"banana",
	"apricot",
	"cherry",
	"clementine",
}

q := Range(1, 10).Join(From(fruits),
	func(i interface{}) interface{} { return i },
	func(i interface{}) interface{} { return len(i.(string)) },
	func(outer interface{}, inner interface{}) interface{} {
		return KeyValue{outer, inner}
	})

fmt.Println(q.Results())
Output:

[{5 apple} {6 banana} {6 cherry} {7 apricot} {10 clementine}]

func (Query) Last

func (q Query) Last() (r interface{})

Last returns the last element of a collection.

func (Query) LastWith

func (q Query) LastWith(predicate func(interface{}) bool) (r interface{})

LastWith returns the last element of a collection that satisfies a specified condition.

func (Query) Max

func (q Query) Max() (r interface{})

Max returns the maximum value in a collection of values.

func (Query) Min

func (q Query) Min() (r interface{})

Min returns the minimum value in a collection of values.

func (Query) OrderBy

func (q Query) OrderBy(
	selector func(interface{}) interface{}) OrderedQuery

OrderBy sorts the elements of a collection in ascending order. Elements are sorted according to a key.

Example
q := Range(1, 10).OrderBy(func(i interface{}) interface{} {
	return i.(int) % 2
}).ThenByDescending(func(i interface{}) interface{} {
	return i
})

fmt.Println(q.Results())
Output:

[10 8 6 4 2 9 7 5 3 1]

func (Query) OrderByDescending

func (q Query) OrderByDescending(
	selector func(interface{}) interface{}) OrderedQuery

OrderByDescending sorts the elements of a collection in descending order. Elements are sorted according to a key.

func (Query) Prepend

func (q Query) Prepend(item interface{}) Query

Prepend inserts an item to the beginning of a collection, so it becomes the first item.

func (Query) Results

func (q Query) Results() (r []interface{})

Results iterates over a collection and returnes slice of interfaces

func (Query) Reverse

func (q Query) Reverse() Query

Reverse inverts the order of the elements in a collection.

Unlike OrderBy, this sorting method does not consider the actual values themselves in determining the order. Rather, it just returns the elements in the reverse order from which they are produced by the underlying source.

func (Query) Select

func (q Query) Select(selector func(interface{}) interface{}) Query

Select projects each element of a collection into a new form. Returns a query with the result of invoking the transform function on each element of original source.

This projection method requires the transform function, selector, to produce one value for each value in the source collection. If selector returns a value that is itself a collection, it is up to the consumer to traverse the subcollections manually. In such a situation, it might be better for your query to return a single coalesced collection of values. To achieve this, use the SelectMany method instead of Select. Although SelectMany works similarly to Select, it differs in that the transform function returns a collection that is then expanded by SelectMany before it is returned.

func (Query) SelectIndexed

func (q Query) SelectIndexed(selector func(int, interface{}) interface{}) Query

SelectIndexed projects each element of a collection into a new form by incorporating the element's index. Returns a query with the result of invoking the transform function on each element of original source.

The first argument to selector represents the zero-based index of that element in the source collection. This can be useful if the elements are in a known order and you want to do something with an element at a particular index, for example. It can also be useful if you want to retrieve the index of one or more elements. The second argument to selector represents the element to process.

This projection method requires the transform function, selector, to produce one value for each value in the source collection. If selector returns a value that is itself a collection, it is up to the consumer to traverse the subcollections manually. In such a situation, it might be better for your query to return a single coalesced collection of values. To achieve this, use the SelectMany method instead of Select. Although SelectMany works similarly to Select, it differs in that the transform function returns a collection that is then expanded by SelectMany before it is returned.

func (Query) SelectMany

func (q Query) SelectMany(selector func(interface{}) Query) Query

SelectMany projects each element of a collection to a Query, iterates and flattens the resulting collection into one collection.

Example
input := [][]int{{1, 2, 3}, {4, 5, 6, 7}}

q := From(input).SelectMany(func(i interface{}) Query {
	return From(i)
})

fmt.Println(q.Results())
Output:

[1 2 3 4 5 6 7]

func (Query) SelectManyBy

func (q Query) SelectManyBy(
	selector func(interface{}) Query,
	resultSelector func(interface{}, interface{}) interface{},
) Query

SelectManyBy projects each element of a collection to a Query, iterates and flattens the resulting collection into one collection, and invokes a result selector function on each element therein.

func (Query) SelectManyByIndexed

func (q Query) SelectManyByIndexed(selector func(int, interface{}) Query,
	resultSelector func(interface{}, interface{}) interface{}) Query

SelectManyByIndexed projects each element of a collection to a Query, iterates and flattens the resulting collection into one collection, and invokes a result selector function on each element therein. The index of each source element is used in the intermediate projected form of that element.

func (Query) SelectManyIndexed

func (q Query) SelectManyIndexed(selector func(int, interface{}) Query) Query

SelectManyIndexed projects each element of a collection to a Query, iterates and flattens the resulting collection into one collection.

The first argument to selector represents the zero-based index of that element in the source collection. This can be useful if the elements are in a known order and you want to do something with an element at a particular index, for example. It can also be useful if you want to retrieve the index of one or more elements. The second argument to selector represents the element to process.

func (Query) SequenceEqual

func (q Query) SequenceEqual(q2 Query) bool

SequenceEqual determines whether two collections are equal.

func (Query) Single

func (q Query) Single() interface{}

Single returns the only element of a collection, and nil if there is not exactly one element in the collection.

func (Query) SingleWith

func (q Query) SingleWith(predicate func(interface{}) bool) (r interface{})

SingleWith returns the only element of a collection that satisfies a specified condition, and nil if more than one such element exists.

func (Query) Skip

func (q Query) Skip(count int) Query

Skip bypasses a specified number of elements in a collection and then returns the remaining elements.

func (Query) SkipWhile

func (q Query) SkipWhile(predicate func(interface{}) bool) Query

SkipWhile bypasses elements in a collection as long as a specified condition is true and then returns the remaining elements.

This method tests each element by using predicate and skips the element if the result is true. After the predicate function returns false for an element, that element and the remaining elements in source are returned and there are no more invocations of predicate.

func (Query) SkipWhileIndexed

func (q Query) SkipWhileIndexed(predicate func(int, interface{}) bool) Query

SkipWhileIndexed bypasses elements in a collection as long as a specified condition is true and then returns the remaining elements. The element's index is used in the logic of the predicate function.

This method tests each element by using predicate and skips the element if the result is true. After the predicate function returns false for an element, that element and the remaining elements in source are returned and there are no more invocations of predicate.

func (Query) Sort

func (q Query) Sort(less func(i, j interface{}) bool) Query

Sort returns a new query by sorting elements with provided less function in ascending order. The comparer function should return true if the parameter i is less than j. While this method is uglier than chaining OrderBy, OrderByDescending, ThenBy and ThenByDescending methods, it's performance is much better.

func (Query) SumFloats

func (q Query) SumFloats() (r float64)

SumFloats computes the sum of a collection of numeric values.

Values can be of any float type: float32 or float64. The result is float64. Method returns zero if collection contains no elements.

func (Query) SumInts

func (q Query) SumInts() (r int64)

SumInts computes the sum of a collection of numeric values.

Values can be of any integer type: int, int8, int16, int32, int64. The result is int64. Method returns zero if collection contains no elements.

func (Query) SumUInts

func (q Query) SumUInts() (r uint64)

SumUInts computes the sum of a collection of numeric values.

Values can be of any unsigned integer type: uint, uint8, uint16, uint32, uint64. The result is uint64. Method returns zero if collection contains no elements.

func (Query) Take

func (q Query) Take(count int) Query

Take returns a specified number of contiguous elements from the start of a collection.

func (Query) TakeWhile

func (q Query) TakeWhile(predicate func(interface{}) bool) Query

TakeWhile returns elements from a collection as long as a specified condition is true, and then skips the remaining elements.

func (Query) TakeWhileIndexed

func (q Query) TakeWhileIndexed(predicate func(int, interface{}) bool) Query

TakeWhileIndexed returns elements from a collection as long as a specified condition is true. The element's index is used in the logic of the predicate function. The first argument of predicate represents the zero-based index of the element within collection. The second argument represents the element to test.

func (Query) ToChannel

func (q Query) ToChannel(result chan<- interface{})

ToChannel iterates over a collection and outputs each element to a channel, then closes it.

Example
c := make(chan interface{})

go func() {
	Repeat(10, 3).ToChannel(c)
}()

for i := range c {
	fmt.Println(i)
}
Output:

10
10
10

func (Query) ToMap

func (q Query) ToMap(result interface{})

ToMap iterates over a collection and populates result map with elements. Collection elements have to be of KeyValue type to use this method. To populate a map with elements of different type use ToMapBy method.

func (Query) ToMapBy

func (q Query) ToMapBy(
	result interface{},
	keySelector func(interface{}) interface{},
	valueSelector func(interface{}) interface{},
)

ToMapBy iterates over a collection and populates result map with elements. Functions keySelector and valueSelector are executed for each element of the collection to generate key and value for the map. Generated key and value types must be assignable to the map's key and value types.

Example
input := [][]interface{}{{1, true}}

result := make(map[int]bool)
From(input).ToMapBy(&result,
	func(i interface{}) interface{} {
		return i.([]interface{})[0]
	},
	func(i interface{}) interface{} {
		return i.([]interface{})[1]
	})

fmt.Println(result)
Output:

map[1:true]

func (Query) ToSlice

func (q Query) ToSlice(result interface{})

ToSlice iterates over a collection and populates result slice with elements. Collection elements must be assignable to the slice's element type.

Example
result := []int{}
Range(1, 10).ToSlice(&result)

fmt.Println(result)
Output:

[1 2 3 4 5 6 7 8 9 10]

func (Query) Union

func (q Query) Union(q2 Query) Query

Union produces the set union of two collections.

This method excludes duplicates from the return set. This is different behavior to the Concat method, which returns all the elements in the input collection including duplicates.

Example
q := Range(1, 10).Union(Range(6, 10))

fmt.Println(q.Results())
Output:

[1 2 3 4 5 6 7 8 9 10 11 12 13 14 15]

func (Query) Where

func (q Query) Where(predicate func(interface{}) bool) Query

Where filters a collection of values based on a predicate.

func (Query) WhereIndexed

func (q Query) WhereIndexed(predicate func(int, interface{}) bool) Query

WhereIndexed filters a collection of values based on a predicate. Each element's index is used in the logic of the predicate function.

The first argument represents the zero-based index of the element within collection. The second argument of predicate represents the element to test.

func (Query) Zip

func (q Query) Zip(
	q2 Query,
	resultSelector func(interface{}, interface{}) interface{},
) Query

Zip applies a specified function to the corresponding elements of two collections, producing a collection of the results.

The method steps through the two input collections, applying function resultSelector to corresponding elements of the two collections. The method returns a collection of the values that are returned by resultSelector. If the input collections do not have the same number of elements, the method combines elements until it reaches the end of one of the collections. For example, if one collection has three elements and the other one has four, the result collection has only three elements.

Example
number := []int{1, 2, 3, 4, 5}
words := []string{"one", "two", "three"}

q := From(number).Zip(From(words), func(a interface{}, b interface{}) interface{} {
	return []interface{}{a, b}
})

fmt.Println(q.Results())
Output:

[[1 one] [2 two] [3 three]]

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL