linq

package module
v2.1.0 Latest Latest
Warning

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

Go to latest
Published: Jul 19, 2023 License: MIT Imports: 4 Imported by: 1

README

LINQ for Go with type parameters

LINQ (Language-Integrated Query) is a component that adds data querying capabilities of Microsoft .Net languages. This package provides the implementation of the LINQ functions for Go with type parameters.

Quick Start

Install
go get github.com/makiuchi-d/linq/v2
Example
package main

import (
	"fmt"

	"github.com/makiuchi-d/linq/v2"
)

type Student struct {
	Name  string
	Class string
	Score int
}

func main() {
	students := []Student{
		// generated by https://testdata.userlocal.jp/
		{"熊木 緑", "1-A", 953},
		{"山本 千佳子", "1-C", 559},
		{"星 雅彦", "1-B", 136},
		{"齊藤 綾子", "1-A", 149},
		{"杉原 和己", "1-C", 737},
		{"山路 信之", "1-B", 425},
		{"佐々木 淑子", "1-C", 759},
		{"三宅 直人", "1-B", 594},
		{"緒方 俊", "1-B", 405},
		{"稲井 隆生", "1-A", 495},
	}

	e1 := linq.FromSlice(students)
	e2 := linq.Where(e1, func(s Student) (bool, error) { return s.Class == "1-B", nil })
	e3 := linq.OrderByDescending(e2, func(s Student) (int, error) { return s.Score, nil })

	linq.ForEach(e3, func(s Student) error {
		fmt.Printf("%d %s\n", s.Score, s.Name)
		return nil
	})
}

Output:

594 三宅 直人
425 山路 信之
405 緒方 俊
136 星 雅彦

Functions

italics are unique to this package.

Sorting Data
  • OrderBy
  • OrderByDescending
  • OrderByFunc
  • ThenBy
  • ThenByDescending
  • Reverse
Set Operations
  • Distinct
  • DistinctBy
  • Except
  • ExceptBy
  • Intersect
  • IntersectBy
  • Union
  • UnionBy
Filtering Data
  • Where
Quantifier Operations
  • All
  • Any
  • Contains
  • ContainsFunc
Projection Operations
  • Select
  • SelectMany
  • Zip
Partitioning Data
  • Skip
  • SkipLast
  • SkipWhile
  • Take
  • TakeLast
  • TakeWhile
  • Chunk
Join Operations
  • GroupJoin
  • Join
Grouping Data
  • GroupBy
Generation Operations
  • DefaultIfEmpty
  • Empty
  • Range
  • Repeat
Element Operations
  • ElementAt
  • ElementAtOrDefault
  • First
  • FirstOrDefault
  • Last
  • LastOrDefault
  • Single
  • SingleOrDefault
Converting Data Types
  • FromMap
  • FromSlice
  • ToMap
  • ToMapFunc
  • ToSlice
Concatenation Operations
  • Concat
Aggregation Operations
  • Aggregate
  • Average
  • Count
  • Max
  • MaxBy
  • MaxByFunc
  • Min
  • MinBy
  • MinByFunc
  • Sum
  • Sumf
Other
  • ForEach
  • Generator

C# LINQ Documents

Standard Query Operators
Sorting Data
Set Operations
Filtering Data
Quantifier Operations
Projection Operations
Partitioning Data
Join Operations
Grouping Data
Generation Operations
Equality Operations
Element Operations
Converting Data Types
Concatenation Operations
Aggregation Operations

Documentation

Overview

LINQ for Go with type parameters

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Aggregate

func Aggregate[S, T any, E IEnumerable[S]](src E, seed T, fn func(acc T, v S) (T, error)) (T, error)

Aggregate applies an accumulator function over a sequence.

func All

func All[T any, E IEnumerable[T]](src E, pred func(v T) (bool, error)) (bool, error)

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

func Any

func Any[T any, E IEnumerable[T]](src E, pred func(v T) (bool, error)) (bool, error)

Any determines whether any element of a sequence satisfies a condition.

func Average

func Average[T Real, E IEnumerable[T]](src E) (float64, error)

Average computes the average of a sequence of numeric (real number) values.

func Contains

func Contains[T comparable, E IEnumerable[T]](src E, val T) (bool, error)

Contains cetermines whether a sequence contains a specified element.

func ContainsFunc

func ContainsFunc[T any, E IEnumerable[T]](src E, val T, equals func(T, T) (bool, error)) (bool, error)

ContainsFunc determines whether a sequence contains a specified element by using a specified comparer function.

func Count

func Count[T any, E IEnumerable[T]](src E) (int, error)

Count returns a number that represents how many elements in the specified sequence

func ElementAt

func ElementAt[T any, E IEnumerable[T]](src E, n int) (def T, err error)

ElementAt returns the element at a specified index in a sequence.

func ElementAtOrDefault

func ElementAtOrDefault[T any, E IEnumerable[T]](src E, n int) (T, error)

ElementAtOrDefault returns the element at a specified index in a sequence or a default value if the index is out of range.

func First

func First[T any, E IEnumerable[T]](src E) (def T, _ error)

First returns the first element in a sequence

func FirstOrDefault

func FirstOrDefault[T any, E IEnumerable[T]](src E, defaultValue T) (T, error)

FirstOrDefault returns the first element of the sequence, or a specified default value if no such element is found.

func ForEach

func ForEach[T any, E IEnumerable[T]](src E, f func(T) error) error

ForEach performs the specified function on each element of the specified enumerator.

func Last

func Last[T any, E IEnumerable[T]](src E) (def T, _ error)

Last returns the last element of a sequence that satisfies a specified condition.

func LastOrDefault

func LastOrDefault[T any, E IEnumerable[T]](src E, defaultValue T) (T, error)

LastOrDefault returns the last element of a sequence that satisfies a condition, or a specified default value if no such element is found.

func Max

func Max[T constraints.Ordered, E IEnumerable[T]](src E) (def T, _ error)

Maxby returns the maximum value in a sequence of values.

func MaxBy

func MaxBy[T any, K constraints.Ordered, E IEnumerable[T]](src E, keySelector func(T) (K, error)) (def T, _ error)

MaxBy returns the maximum value in a generic sequence according to a specified key selector function.

func MaxByFunc

func MaxByFunc[T any, E IEnumerable[T]](src E, greater func(a, b T) (bool, error)) (def T, _ error)

MaxByFunc returns the maximum value in a generic sequence according to a comparer function.

func Min

func Min[T constraints.Ordered, E IEnumerable[T]](src E) (def T, _ error)

Min returns the minimum value in a sequence of values.

func MinBy

func MinBy[T any, K constraints.Ordered, E IEnumerable[T]](src E, keySelector func(T) (K, error)) (def T, _ error)

MinBy returns the minimum value in a generic sequence according to a specified key selector function.

func MinByFunc

func MinByFunc[T any, E IEnumerable[T]](src E, less func(a, b T) (bool, error)) (def T, _ error)

MinByFunc returns the minimum value in a generic sequence according to a comparer function.

func Single

func Single[T any, E IEnumerable[T]](src E) (def T, _ error)

Single returns the only element of a sequence, and return an error InvalidOperation if more than one such element exists.

func SingleOrDefault

func SingleOrDefault[T any, E IEnumerable[T]](src E, defaultValue T) (def T, _ error)

SingleOrDefault returns the only element of a sequence, or a specified default value if no such element exists; this function returns an error InvalidOperation if more than one element satisfies the condition.

func Sum

func Sum[T constraints.Integer, E IEnumerable[T]](src E) (int, error)

Sum calculates the sum of a integer sequence.

func Sumf

func Sumf[T constraints.Float, E IEnumerable[T]](src E) (float64, error)

Sumf calculates the sum of a floating number sequence.

func ToMap

func ToMap[K comparable, V any, E IEnumerable[KeyValue[K, V]]](src E) (map[K]V, error)

ToMap creates a map[K]V from an IEnumerable[T]. T must be a type KeyValue[K, V].

func ToMapFunc

func ToMapFunc[T any, K comparable, V any, E IEnumerable[T]](src E, selector func(T) (K, V, error)) (map[K]V, error)

ToMapFunc creates a map[K]V from an IEnumerable[T] according to specified key-value selector function.

func ToSlice

func ToSlice[T any, E IEnumerable[T]](src E) ([]T, error)

ToSlice creates a slice from an IEnumerable[T]

Types

type Enumerable

type Enumerable[T any] func() Enumerator[T]

Enumerable[T] is an implementation of IEnumerable[T].

func Chunk

func Chunk[T any, E IEnumerable[T]](src E, size int) Enumerable[[]T]

Chunk splits the elements of a sequence into chunks of size at most `size`.

func Concat

func Concat[T any, E IEnumerable[T]](first, second E) Enumerable[T]

Concat concatenates two sequences.

func DefaultIfEmpty

func DefaultIfEmpty[T any, E IEnumerable[T]](src E, defaultValue T) Enumerable[T]

DefaultIfEmpty returns the elements of the specified sequence or the specified value in a singleton collection if the sequence is empty.

func Distinct

func Distinct[T any, E IEnumerable[T]](src E, equals func(T, T) (bool, error), getHashCode func(T) (int, error)) Enumerable[T]

Distinct returns distinct elements from a sequence by using the specified comparer functions.

func DistinctBy

func DistinctBy[T any, K comparable, E IEnumerable[T]](src E, keySelector func(v T) (K, error)) Enumerable[T]

DistinctBy returns distinct elements from a sequence according to a specified key selector function.

func Empty

func Empty[T any]() Enumerable[T]

Empty returns an empty IEnumerable[T] that has the specified type argument.

func Except

func Except[T any, E IEnumerable[T]](first, second E, equals func(T, T) (bool, error), getHashCode func(T) (int, error)) Enumerable[T]

Except produces the set difference of two sequences by using the specified comparer functions.

func ExceptBy

func ExceptBy[T any, K comparable, E IEnumerable[T]](first, second E, keySelector func(v T) (K, error)) Enumerable[T]

ExceptBy produces the set difference of two sequences according to a specified key selector function.

func FromMap

func FromMap[T ~map[K]V, K comparable, V any](m T) Enumerable[KeyValue[K, V]]

FromMap generates an IEnumerable[T] from a map.

func FromSlice

func FromSlice[S ~[]T, T any](s S) Enumerable[T]

FromSlice generates an IEnumerable[T] from a slice.

func Generator added in v2.1.0

func Generator[T any](ctx context.Context, g func(yield func(T) error) error) Enumerable[T]

Generator makes the given function an enumerator generator.

Example
ctx, cancel := context.WithCancel(context.Background())
defer cancel()

gen := linq.Generator(ctx, func(yield func(int) error) error {
	for i := 0; i < 10; i++ {
		err := yield(i)
		if err != nil {
			return err
		}
	}
	return nil
})

r, err := linq.ToSlice(gen)
if err != nil {
	panic(err)
}
fmt.Println(r)
Output:

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

func GroupBy

func GroupBy[T any, K comparable, E IEnumerable[T]](src E, keySelector func(T) (K, error)) Enumerable[Grouping[T, K]]

GroupBy groups the elements of a sequence according to a specified key selector function.

func GroupJoin

func GroupJoin[S1, S2, T any, K comparable, E1 IEnumerable[S1], E2 IEnumerable[S2]](
	outer E1,
	inner E2,
	outerKeySelector func(S1) (K, error),
	innerKeySelector func(S2) (K, error),
	resultSelector func(S1, Enumerable[S2]) (T, error),
) Enumerable[T]

GroupJoin correlates the elements of two sequences based on equality of keys and groups the results.

func Intersect

func Intersect[T any, E IEnumerable[T]](first, second E, equals func(T, T) (bool, error), getHashCode func(T) (int, error)) Enumerable[T]

Intersect produces the set intersection of two sequences by using the specified comparer functions.

func IntersectBy

func IntersectBy[T any, K comparable, E IEnumerable[T]](first, second E, keySelector func(v T) (K, error)) Enumerable[T]

IntersectBy produces the set intersection of two sequences according to a specified key selector function.

func Join

func Join[S1, S2, T any, K comparable, E1 IEnumerable[S1], E2 IEnumerable[S2]](
	outer E1,
	inner E2,
	outerKeySelector func(S1) (K, error),
	innerKeySelector func(S2) (K, error),
	resultSelector func(S1, S2) (T, error),
) Enumerable[T]

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

func OrderByFunc

func OrderByFunc[T any, E IEnumerable[T]](src E, less func(a, b T) bool) Enumerable[T]

OrderByFunc sorts the elements of a sequence by the provided less function.

func Range

func Range(start, count int) Enumerable[int]

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

func Repeat

func Repeat[T any](v T, n int) Enumerable[T]

Repeat generates a sequence that contains one repeated value.

func Reverse

func Reverse[T any, E IEnumerable[T]](src E) Enumerable[T]

Reverse inverts the order of the elements in a sequence.

func Select

func Select[S, T any, E IEnumerable[S]](src E, selector func(v S) (T, error)) Enumerable[T]

Select projects each element of a sequence into a new form.

func SelectMany

func SelectMany[S, C, T any, E IEnumerable[S], EC IEnumerable[C]](src E, collectionSelector func(S) (EC, error), resultSelector func(C) (T, error)) Enumerable[T]

SelectMany projects each element of a sequence to an Enumerable[T] and flattens the resulting sequences into one sequence.

func Skip

func Skip[T any, E IEnumerable[T]](src E, count int) Enumerable[T]

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

func SkipLast

func SkipLast[T any, E IEnumerable[T]](src E, count int) Enumerable[T]

SkipLast returns a new enumerable collection that contains the elements from source with the last count elements of the source collection omitted.

func SkipWhile

func SkipWhile[T any, E IEnumerable[T]](src E, pred func(T) (bool, error)) Enumerable[T]

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

func Take

func Take[T any, E IEnumerable[T]](src E, count int) Enumerable[T]

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

func TakeLast

func TakeLast[T any, E IEnumerable[T]](src E, count int) Enumerable[T]

TakeLast returns a new enumerable collection that contains the last count elements from source.

func TakeWhile

func TakeWhile[T any, E IEnumerable[T]](src E, pred func(T) (bool, error)) Enumerable[T]

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

func Union

func Union[T any, E IEnumerable[T]](first, second E, equals func(T, T) (bool, error), getHashCode func(T) (int, error)) Enumerable[T]

Union produces the set union of two sequences by using the specified comparer functions.

func UnionBy

func UnionBy[T any, K comparable, E IEnumerable[T]](first, second E, keySelector func(v T) (K, error)) Enumerable[T]

UnionBy produces the set union of two sequences according to a specified key selector function.

func Where

func Where[T any, E IEnumerable[T]](src E, pred func(v T) (bool, error)) Enumerable[T]

Where filters a sequence of values based on a predicate.

func Zip

func Zip[S1, S2, T any, E1 IEnumerable[S1], E2 IEnumerable[S2]](first E1, second E2, resultSelector func(S1, S2) (T, error)) Enumerable[T]

Zip applies a specified function to the corresponding elements of two sequences, producing a sequence of the results.

type Enumerator

type Enumerator[T any] interface {
	// Next returns a next element of this collection.
	// It returns EOC as an `error` when it reaches the end of the collection.
	Next() (T, error)
}

Enumerator[T] is an enumerator of the collection.

type Error

type Error string

Error : LINQ error type.

const (
	// EOC : End of the collection.
	EOC Error = "End of the collection"

	// OutOfRange : Index out of range.
	OutOfRange Error = "Out of range"

	// InvalidOperation : Invalid operation such as no element satisfying the condition.
	InvalidOperation Error = "Invalid operation"
)

func (Error) Error

func (e Error) Error() string

type Grouping

type Grouping[T any, K comparable] struct {
	Enumerable Enumerable[T]
	Key        K
}

Grouping represents a collection of objects that have a common key.

type IEnumerable

type IEnumerable[T any] interface {
	Enumerable[T] | OrderedEnumerable[T]
}

IEnumerable[T] is a queryable collection.

type KeyValue

type KeyValue[K comparable, V any] struct {
	Key   K
	Value V
}

KeyValue pair as an element of map[K]V

type OrderedEnumerable

type OrderedEnumerable[T any] func() Enumerator[T]

OrderedEnumerable[T] is an implementation of IEnumerable[T], which is generated by OrderBy or ThenBy.

func OrderBy

func OrderBy[T any, K constraints.Ordered, E IEnumerable[T]](src E, keySelector func(T) (K, error)) OrderedEnumerable[T]

OrderBy sorts the elements of a sequence in ascending order according to a key.

func OrderByDescending

func OrderByDescending[T any, K constraints.Ordered, E IEnumerable[T]](src E, keySelector func(T) (K, error)) OrderedEnumerable[T]

OrderByDescending sorts the elements of a sequence in descending order according to a key.

func ThenBy

func ThenBy[T any, K constraints.Ordered](src OrderedEnumerable[T], keySelector func(T) (K, error)) OrderedEnumerable[T]

ThenBy performs a subsequent ordering of the elements in a sequence in ascending order according to a key.

func ThenByDescending

func ThenByDescending[T any, K constraints.Ordered](src OrderedEnumerable[T], keySelector func(T) (K, error)) OrderedEnumerable[T]

ThenByDescending performs a subsequent ordering of the elements in a sequence in descending order, according to a key.

type Real

type Real interface {
	constraints.Integer | constraints.Float
}

Jump to

Keyboard shortcuts

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