linq

package module
v1.2.1 Latest Latest
Warning

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

Go to latest
Published: Nov 7, 2023 License: MIT Imports: 5 Imported by: 9

README

Go-Linq

licensecode sizeopen issuesclosed issues go versionlatest version

GitHub Super-LinterGo Report CardCoverage Status

C# System.Linq Enumerable methods and System.Collections.Generic List realization by go generic.

Notice

golang version must be greater than v1.18

for previous go versions (<1.18), you can try this one.

Usage

install package

go get github.com/STRockefeller/go-linq

import package

import "github.com/STRockefeller/go-linq"

enjoy

func linqTest() {
 type user struct {
  name string
  age  int
 }
 users := linq.New([]user{})
 users.Add(user{
  name: "Rockefeller",
  age:  27,
 })
 users.Prepend(user{
  name: "newUser",
  age:  18,
 })
 adultsCount := users.Where(func(u user) bool { return u.age >= 18 }).Count(func(u user) bool {return true})
 fmt.Println("there are ",adultsCount,"adults in users.")
}

See pkg.go.dev document for details

Benchmark

compare with another linq package.

package main

import (
 "fmt"
 "testing"

 STRLinq "github.com/STRockefeller/go-linq"
 AHMLinq "github.com/ahmetb/go-linq/v3"
)

var testStrings = []string{"Oh,", "mister", "ocean", "fish", "!"}
var testIntegers = []int{7, 5, 3, 9, 5, 1, 7, 4, 1, 0, 3, 6, 9}

func BenchmarkSTRockefeller_linq(b *testing.B) {
 for i := 0; i < b.N; i++ {
  STRLinq.New(testStrings).Where(func(s string) bool { return len(s) >= 3 }).Skip(1).Contains("mister")

  mySlice := STRLinq.New(testIntegers).Distinct().Where(func(i int) bool { return i > 3 }).ToSlice()

  if false {
   fmt.Print(mySlice)
  }
 }
}

func BenchmarkAhmetb_linq(b *testing.B) {
 for i := 0; i < b.N; i++ {
  AHMLinq.From(testStrings).Where(func(i interface{}) bool { return len(i.(string)) >= 3 }).Skip(1).Contains("mister")

  var mySlice []int
  AHMLinq.From(testIntegers).Distinct().Where(func(i interface{}) bool { return i.(int) > 3 }).ToSlice(&mySlice)

  if false {
   fmt.Print(mySlice)
  }
 }
}

result

goos: windows
goarch: amd64
pkg: test
cpu: Intel(R) Core(TM) i7-9700 CPU @ 3.00GHz
BenchmarkSTRockefeller_linq-8     2529393        467.3 ns/op      400 B/op       12 allocs/op
BenchmarkAhmetb_linq-8             521704       2121 ns/op     1080 B/op       45 allocs/op
PASS
coverage: [no statements]
ok   test 3.004s

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ConvertToMapWithKey added in v0.1.5

func ConvertToMapWithKey[TSource any, TKey comparable](items []TSource, keySelector func(TSource) TKey) map[TKey]TSource

Creates a map[TKey]TSource from an linq[TSource] according to a specified key selector function.

func ConvertToMapWithKeyValue added in v0.1.5

func ConvertToMapWithKeyValue[TSource any, TKey comparable, TValue any](items []TSource, keySelector func(TSource) TKey, valueSelector func(TSource) TValue) map[TKey]TValue

Creates a map[TKey,TValue] from an linq[TSource] according to specified key selector and element selector functions.

func GroupBy added in v0.1.7

func GroupBy[L any, K comparable, E any](items []L, key func(L) K, element func(L) E) map[K][]E

func NoPredict added in v1.0.2

func NoPredict[T any]() func(T) bool

func RunInAsync added in v0.1.2

func RunInAsync[I comparable, O any](inputs Linq[I], delegate func(I) O) []O

Types

type Linq

type Linq[T any] interface {
	// All determines whether all elements of a sequence satisfy a condition.
	All(predicate func(T) bool) bool
	// Any determines whether any element of a sequence satisfies a condition.
	Any(predicate func(T) bool) bool
	// Append appends a value to the end of the sequence.
	Append(t ...T) Linq[T]
	// Clone returns a copy of linq[T]
	Clone() Linq[T]
	// Contains determines whether a sequence contains a specified element.
	Contains(target T) bool
	// Count returns a number that represents how many elements in the specified sequence satisfy a condition.
	Count(predicate func(T) bool) int
	// Distinct returns distinct elements from a sequence by using the default equality comparer to compare values.
	Distinct() Linq[T]
	// ElementAt returns the element at a specified index in a sequence.
	// ! this method panics when index is out of range.
	ElementAt(index int) T
	// ElementAtOrDefault returns the element at a specified index in a sequence or a default value if the index is out of range.
	ElementAtOrDefault(index int) T
	// Empty returns an empty linq[T] that has the specified type argument.
	Empty() Linq[T]
	// Exists determines whether the linq[T] contains elements that match the conditions defined by the specified predicate.
	Exists(predicate func(T) bool) bool
	// Find Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire linq[T].
	Find(predicate func(T) bool) T
	// FindAll retrieves all the elements that match the conditions defined by the specified predicate.
	FindAll(predicate func(T) bool) Linq[T]
	// FindIndex searches for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the first occurrence within the entire linq[T].
	FindIndex(predicate func(T) bool) int
	// FindLast searches for an element that matches the conditions defined by the specified predicate, and returns the last occurrence within the entire linq[T].
	FindLast(predicate func(T) bool) T
	// FindLastIndex searches for an element that matches the conditions defined by a specified predicate, and returns the zero-based index of the last occurrence within the linq[T] or a portion of it.
	FindLastIndex(predicate func(T) bool) int
	// First returns the first element in a sequence that satisfies a specified condition.
	// ! this method panics when no element is found.
	First(predicate func(T) bool) T
	// FirstOrDefault returns the first element of a sequence, or a default value if the sequence contains no elements.
	FirstOrDefault(predicate func(T) bool) T
	// ForEach performs the specified action on each element of the linq[T].
	ForEach(callBack func(T))
	// Last returns the last element of a sequence.
	// ! this method panics when no element is found.
	Last(predicate func(T) bool) T
	// LastOrDefault returns the last element of a sequence, or a specified default value if the sequence contains no elements.
	LastOrDefault(predicate func(T) bool) T
	// OrderBy sorts the elements of a sequence in ascending order according to a key.
	OrderBy(comparer func(T) int) Linq[T]
	// OrderByDescending sorts the elements of a sequence in descending order according to a key.
	OrderByDescending(comparer func(T) int) Linq[T]
	// Prepend adds a value to the beginning of the sequence.
	Prepend(t ...T) Linq[T]
	// ReplaceAll replaces old values by new values
	ReplaceAll(oldValue T, newValue T) Linq[T]
	// Reverse inverts the order of the elements in a sequence.
	Reverse() Linq[T]
	RunInAsyncWithRoutineLimit(delegate func(T), limit int)
	// Single returns the only element of a sequence that satisfies a specified condition, and panics if more than one such element exists.
	Single(predicate func(T) bool) T
	// SingleOrDefault returns the only element of a sequence, or a default value of T if the sequence is empty.
	SingleOrDefault(predicate func(T) bool) T
	// Skip bypasses a specified number of elements in a sequence and then returns the remaining elements.
	// ! this method panics when count is out of range.
	Skip(count int) Linq[T]
	// SkipLast returns a new enumerable collection that contains the elements from source with the last count elements of the source collection omitted.
	// ! this method panics when count is out of range.
	SkipLast(count int) Linq[T]
	// SkipWhile bypasses elements in a sequence 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.
	SkipWhile(predicate func(T) bool) Linq[T]
	// Take returns a specified number of contiguous elements from the start of a sequence.
	// ! this method panics when count is out of range.
	Take(count int) Linq[T]
	// TakeLast returns a new enumerable collection that contains the last count elements from source.
	// ! this method panics when count is out of range.
	TakeLast(count int) Linq[T]
	// TakeWhile returns elements from a sequence as long as a specified condition is true. The element's index is used in the logic of the predicate function.
	TakeWhile(predicate func(T) bool) Linq[T]
	// ToChannel creates a channel with values in linq[T]
	ToChannel() <-chan T
	// ToChannelWithBuffer creates a channel with values in linq[T] with specified buffer. (async method)
	ToChannelWithBuffer(buffer int) <-chan T
	// Creates a map[interface{}]T from an linq[T] according to a specified key selector function.
	ToMapWithKey(keySelector func(T) interface{}) map[interface{}]T
	// Creates a map[interface{}]interface from an linq[T] according to a specified key selector function.
	ToMapWithKeyValue(keySelector func(T) interface{}, valueSelector func(T) interface{}) map[interface{}]interface{}
	// ToSlice creates a slice from a linq[T].
	ToSlice() []T
	// Where filters a sequence of values based on a predicate.
	Where(predicate func(T) bool) Linq[T]
	// Length returns the number of items in the linq[T] collection.
	Length() int

	// Add adds an object to the end of the linq[T].
	Add(element T)
	// AddRange adds the elements of the specified collection to the end of the linq[T].
	AddRange(collection []T)
	// Remove removes the first occurrence of a specific object from the linq[T].
	Remove(item T) bool
	// RemoveAll removes all the elements that match the conditions defined by the specified predicate.
	RemoveAll(predicate func(T) bool) int
	// RemoveAt removes the element at the specified index of the linq[T].
	RemoveAt(index int)
	// RemoveRange removes a range of elements from the linq[T].
	RemoveRange(index int, count int) error
	// Clear removes all elements from the linq[T].
	Clear()
}

func New added in v1.1.0

func New[T any](slice []T) Linq[T]

linq constructor

func NewFromChannel added in v1.0.5

func NewFromChannel[T any](c <-chan T) Linq[T]

linq constructor ! Make sure to close the channel when you are done sending elements to it.

func NewFromMap added in v1.0.5

func NewFromMap[K comparable, V any, T any](m map[K]V, delegate func(K, V) T) Linq[T]

linq constructor

func OrderBy added in v0.1.1

func OrderBy[L any, O constraints.Ordered](items []L, comparer func(L) O) Linq[L]

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

func OrderByDescending added in v0.1.1

func OrderByDescending[L any, O constraints.Ordered](items []L, comparer func(L) O) Linq[L]

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

func Repeat

func Repeat[T any](element T, count int) Linq[T]

Repeat generates a sequence that contains one repeated value.

func Select added in v0.1.6

func Select[T, S any](items []T, delegate func(T) S) Linq[S]

Select projects each element of linq into a new form by incorporating the element's index.

func SelectMany added in v1.0.4

func SelectMany[T any, U any](items []T, selector func(T) []U) Linq[U]

SelectMany takes a slice of slices and a selector function, and returns a flattened slice of elements selected by the selector function.

type NumberLinq

type NumberLinq[T any, N number] struct {
	// contains filtered or unexported fields
}

NumberLinq provides following new methods:

  • Sum
  • Max
  • Min

func NewNumberLinq added in v1.0.5

func NewNumberLinq[T any, N number](items []T) NumberLinq[T, N]

func (*NumberLinq) Add added in v1.1.0

func (l *NumberLinq) Add(element T)

Add adds an object to the end of the linq[T].

func (*NumberLinq) AddRange added in v1.1.0

func (l *NumberLinq) AddRange(collection []T)

AddRange adds the elements of the specified collection to the end of the linq[T].

func (NumberLinq) All added in v1.1.0

func (l NumberLinq) All(predicate func(T) bool) bool

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

func (NumberLinq) Any added in v1.1.0

func (l NumberLinq) Any(predicate func(T) bool) bool

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

func (NumberLinq) Append added in v1.1.0

func (l NumberLinq) Append(t ...T) Linq[T]

Append appends a value to the end of the sequence.

func (*NumberLinq) Clear added in v1.1.0

func (l *NumberLinq) Clear()

Clear removes all elements from the linq[T].

func (NumberLinq) Clone added in v1.1.0

func (l NumberLinq) Clone() Linq[T]

Clone returns a copy of linq[T]

func (NumberLinq) Contains added in v1.1.0

func (l NumberLinq) Contains(target T) bool

Contains determines whether a sequence contains a specified element.

func (NumberLinq) Count added in v1.1.0

func (l NumberLinq) Count(predicate func(T) bool) int

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

func (NumberLinq) Distinct added in v1.1.0

func (l NumberLinq) Distinct() Linq[T]

Distinct returns distinct elements from a sequence by using the default equality comparer to compare values.

func (NumberLinq) ElementAt added in v1.1.0

func (l NumberLinq) ElementAt(index int) T

ElementAt returns the element at a specified index in a sequence. ! this method panics when index is out of range.

func (NumberLinq) ElementAtOrDefault added in v1.1.0

func (l NumberLinq) ElementAtOrDefault(index int) T

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

func (NumberLinq) Empty added in v1.1.0

func (l NumberLinq) Empty() Linq[T]

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

func (NumberLinq) Exists added in v1.1.0

func (l NumberLinq) Exists(predicate func(T) bool) bool

Exists determines whether the linq[T] contains elements that match the conditions defined by the specified predicate.

func (NumberLinq) Find added in v1.1.0

func (l NumberLinq) Find(predicate func(T) bool) T

Find Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire linq[T].

func (NumberLinq) FindAll added in v1.1.0

func (l NumberLinq) FindAll(predicate func(T) bool) Linq[T]

FindAll retrieves all the elements that match the conditions defined by the specified predicate.

func (NumberLinq) FindIndex added in v1.1.0

func (l NumberLinq) FindIndex(predicate func(T) bool) int

FindIndex searches for an element that matches the conditions defined by the specified predicate, and returns the zero-based index of the first occurrence within the entire linq[T].

func (NumberLinq) FindLast added in v1.1.0

func (l NumberLinq) FindLast(predicate func(T) bool) T

FindLast searches for an element that matches the conditions defined by the specified predicate, and returns the last occurrence within the entire linq[T].

func (NumberLinq) FindLastIndex added in v1.1.0

func (l NumberLinq) FindLastIndex(predicate func(T) bool) int

FindLastIndex searches for an element that matches the conditions defined by a specified predicate, and returns the zero-based index of the last occurrence within the linq[T] or a portion of it.

func (NumberLinq) First added in v1.1.0

func (l NumberLinq) First(predicate func(T) bool) T

First returns the first element in a sequence that satisfies a specified condition. ! this method panics when no element is found.

func (NumberLinq) FirstOrDefault added in v1.1.0

func (l NumberLinq) FirstOrDefault(predicate func(T) bool) T

FirstOrDefault returns the first element of a sequence, or a default value if the sequence contains no elements.

func (NumberLinq) ForEach added in v1.1.0

func (l NumberLinq) ForEach(callBack func(T))

ForEach performs the specified action on each element of the linq[T].

func (NumberLinq) Last added in v1.1.0

func (l NumberLinq) Last(predicate func(T) bool) T

Last returns the last element of a sequence. ! this method panics when no element is found.

func (NumberLinq) LastOrDefault added in v1.1.0

func (l NumberLinq) LastOrDefault(predicate func(T) bool) T

LastOrDefault returns the last element of a sequence, or a specified default value if the sequence contains no elements.

func (NumberLinq) Length added in v1.2.0

func (l NumberLinq) Length() int

Length returns the number of items in the linq[T] collection.

func (NumberLinq[T, N]) Max

func (nl NumberLinq[T, N]) Max(selector func(T) N) N

func (NumberLinq[T, N]) Min

func (nl NumberLinq[T, N]) Min(selector func(T) N) N

func (NumberLinq) OrderBy added in v1.1.0

func (l NumberLinq) OrderBy(comparer func(T) int) Linq[T]

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

func (NumberLinq) OrderByDescending added in v1.1.0

func (l NumberLinq) OrderByDescending(comparer func(T) int) Linq[T]

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

func (NumberLinq) Prepend added in v1.1.0

func (l NumberLinq) Prepend(t ...T) Linq[T]

Prepend adds a value to the beginning of the sequence.

func (*NumberLinq) Remove added in v1.1.0

func (l *NumberLinq) Remove(item T) bool

Remove removes the first occurrence of a specific object from the linq[T].

func (*NumberLinq) RemoveAll added in v1.1.0

func (l *NumberLinq) RemoveAll(predicate func(T) bool) int

RemoveAll removes all the elements that match the conditions defined by the specified predicate.

func (*NumberLinq) RemoveAt added in v1.1.0

func (l *NumberLinq) RemoveAt(index int)

RemoveAt removes the element at the specified index of the linq[T].

func (*NumberLinq) RemoveRange added in v1.1.0

func (l *NumberLinq) RemoveRange(index, count int) error

RemoveRange removes a range of elements from the linq[T].

func (NumberLinq) ReplaceAll added in v1.1.0

func (l NumberLinq) ReplaceAll(oldValue, newValue T) Linq[T]

ReplaceAll replaces old values by new values

func (NumberLinq) Reverse added in v1.1.0

func (l NumberLinq) Reverse() Linq[T]

Reverse inverts the order of the elements in a sequence.

func (NumberLinq) RunInAsyncWithRoutineLimit added in v1.1.0

func (linq NumberLinq) RunInAsyncWithRoutineLimit(delegate func(T), limit int)

func (NumberLinq) Single added in v1.1.0

func (l NumberLinq) Single(predicate func(T) bool) T

Single returns the only element of a sequence that satisfies a specified condition, and panics if more than one such element exists.

func (NumberLinq) SingleOrDefault added in v1.1.0

func (l NumberLinq) SingleOrDefault(predicate func(T) bool) T

SingleOrDefault returns the only element of a sequence, or a default value of T if the sequence is empty.

func (NumberLinq) Skip added in v1.1.0

func (l NumberLinq) Skip(count int) Linq[T]

Skip bypasses a specified number of elements in a sequence and then returns the remaining elements. ! this method panics when count is out of range.

func (NumberLinq) SkipLast added in v1.1.0

func (l NumberLinq) SkipLast(count int) Linq[T]

SkipLast returns a new enumerable collection that contains the elements from source with the last count elements of the source collection omitted. ! this method panics when count is out of range.

func (NumberLinq) SkipWhile added in v1.1.0

func (l NumberLinq) SkipWhile(predicate func(T) bool) Linq[T]

SkipWhile bypasses elements in a sequence 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.

func (NumberLinq[T, N]) Sum

func (nl NumberLinq[T, N]) Sum(selector func(T) N) N

func (NumberLinq) Take added in v1.1.0

func (l NumberLinq) Take(count int) Linq[T]

Take returns a specified number of contiguous elements from the start of a sequence. ! this method panics when count is out of range.

func (NumberLinq) TakeLast added in v1.1.0

func (l NumberLinq) TakeLast(count int) Linq[T]

TakeLast returns a new enumerable collection that contains the last count elements from source. ! this method panics when count is out of range.

func (NumberLinq) TakeWhile added in v1.1.0

func (l NumberLinq) TakeWhile(predicate func(T) bool) Linq[T]

TakeWhile returns elements from a sequence as long as a specified condition is true. The element's index is used in the logic of the predicate function.

func (NumberLinq) ToChannel added in v1.1.0

func (l NumberLinq) ToChannel() <-chan T

ToChannel creates a channel with values in linq[T]

func (NumberLinq) ToChannelWithBuffer added in v1.1.0

func (l NumberLinq) ToChannelWithBuffer(buffer int) <-chan T

ToChannelWithBuffer creates a channel with values in linq[T] with specified buffer. (async method)

func (NumberLinq) ToMapWithKey added in v1.1.0

func (l NumberLinq) ToMapWithKey(keySelector func(T) interface{}) map[interface{}]T

Creates a map[interface{}]T from an linq[T] according to a specified key selector function.

func (NumberLinq) ToMapWithKeyValue added in v1.1.0

func (l NumberLinq) ToMapWithKeyValue(keySelector func(T) interface{}, valueSelector func(T) interface{}) map[interface{}]interface{}

Creates a map[interface{}]interface from an linq[T] according to a specified key selector function.

func (NumberLinq) ToSlice added in v1.1.0

func (l NumberLinq) ToSlice() []T

ToSlice creates a slice from a linq[T].

func (NumberLinq) Where added in v1.1.0

func (l NumberLinq) Where(predicate func(T) bool) Linq[T]

Where filters a sequence of values based on a predicate.

Jump to

Keyboard shortcuts

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