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 ¶
- type Comparable
- type Group
- type Iterable
- type Iterator
- type KeyValue
- type OrderedQuery
- type Query
- func (q Query) Aggregate(f func(interface{}, interface{}) interface{}) interface{}
- func (q Query) AggregateWithSeed(seed interface{}, f func(interface{}, interface{}) interface{}) interface{}
- func (q Query) All(predicate func(interface{}) bool) bool
- func (q Query) Any() bool
- func (q Query) AnyWith(predicate func(interface{}) bool) bool
- func (q Query) Append(item interface{}) Query
- func (q Query) Average() (r float64)
- func (q Query) Concat(q2 Query) Query
- func (q Query) Contains(value interface{}) bool
- func (q Query) Count() (r int)
- func (q Query) CountWith(predicate func(interface{}) bool) (r int)
- func (q Query) Distinct() Query
- func (q Query) DistinctBy(selector func(interface{}) interface{}) Query
- func (q Query) Except(q2 Query) Query
- func (q Query) ExceptBy(q2 Query, selector func(interface{}) interface{}) Query
- func (q Query) First() interface{}
- func (q Query) FirstWith(predicate func(interface{}) bool) interface{}
- func (q Query) GroupBy(keySelector func(interface{}) interface{}, ...) Query
- func (q Query) GroupJoin(inner Query, outerKeySelector func(interface{}) interface{}, ...) Query
- func (q Query) Intersect(q2 Query) Query
- func (q Query) IntersectBy(q2 Query, selector func(interface{}) interface{}) Query
- func (q Query) Join(inner Query, outerKeySelector func(interface{}) interface{}, ...) Query
- func (q Query) Last() (r interface{})
- func (q Query) LastWith(predicate func(interface{}) bool) (r interface{})
- func (q Query) Max() (r interface{})
- func (q Query) Min() (r interface{})
- func (q Query) OrderBy(selector func(interface{}) interface{}) OrderedQuery
- func (q Query) OrderByDescending(selector func(interface{}) interface{}) OrderedQuery
- func (q Query) Prepend(item interface{}) Query
- func (q Query) Results() (r []interface{})
- func (q Query) Reverse() Query
- func (q Query) Select(selector func(interface{}) interface{}) Query
- func (q Query) SelectIndexed(selector func(int, interface{}) interface{}) Query
- func (q Query) SelectMany(selector func(interface{}) Query) Query
- func (q Query) SelectManyBy(selector func(interface{}) Query, ...) Query
- func (q Query) SelectManyByIndexed(selector func(int, interface{}) Query, ...) Query
- func (q Query) SelectManyIndexed(selector func(int, interface{}) Query) Query
- func (q Query) SequenceEqual(q2 Query) bool
- func (q Query) Single() interface{}
- func (q Query) SingleWith(predicate func(interface{}) bool) (r interface{})
- func (q Query) Skip(count int) Query
- func (q Query) SkipWhile(predicate func(interface{}) bool) Query
- func (q Query) SkipWhileIndexed(predicate func(int, interface{}) bool) Query
- func (q Query) Sort(less func(i, j interface{}) bool) Query
- func (q Query) SumFloats() (r float64)
- func (q Query) SumInts() (r int64)
- func (q Query) SumUInts() (r uint64)
- func (q Query) Take(count int) Query
- func (q Query) TakeWhile(predicate func(interface{}) bool) Query
- func (q Query) TakeWhileIndexed(predicate func(int, interface{}) bool) Query
- func (q Query) ToChannel(result chan<- interface{})
- func (q Query) ToMap(result interface{})
- func (q Query) ToMapBy(result interface{}, keySelector func(interface{}) interface{}, ...)
- func (q Query) ToSlice(result interface{})
- func (q Query) Union(q2 Query) Query
- func (q Query) Where(predicate func(interface{}) bool) Query
- func (q Query) WhereIndexed(predicate func(int, interface{}) bool) Query
- func (q Query) Zip(q2 Query, resultSelector func(interface{}, interface{}) interface{}) Query
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 ¶
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 ¶
FromString initializes a linq query with passed string, linq iterates over runes of string.
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) AnyWith ¶
AnyWith determines whether any element of a collection satisfies a condition.
func (Query) Append ¶
Append inserts an item to the end of a collection, so it becomes the last item.
func (Query) Concat ¶
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) CountWith ¶
CountWith returns a number that represents how many elements in the specified collection satisfy a condition.
func (Query) Distinct ¶
Distinct method returns distinct elements from a collection. The result is an unordered collection that contains no duplicate values.
func (Query) DistinctBy ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
Skip bypasses a specified number of elements in a collection and then returns the remaining elements.
func (Query) SkipWhile ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
Take returns a specified number of contiguous elements from the start of a collection.
func (Query) TakeWhile ¶
TakeWhile returns elements from a collection as long as a specified condition is true, and then skips the remaining elements.
func (Query) TakeWhileIndexed ¶
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 ¶
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) WhereIndexed ¶
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 ¶
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]]