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.
go get github.com/makiuchi-d/linq/v2
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 })
// go1.23.0 or later
for s, err := range e3.All() {
if err != nil {
panic(err)
}
fmt.Printf("%d %s\n", s.Score, s.Name)
}
fmt.Println("----")
// it also works in older go
err := linq.ForEach(e3, func(s Student) error {
fmt.Printf("%d %s\n", s.Score, s.Name)
return nil
})
if err != nil {
panic(err)
}
}
Output:
594 三宅 直人
425 山路 信之
405 緒方 俊
136 星 雅彦
----
594 三宅 直人
425 山路 信之
405 緒方 俊
136 星 雅彦
italics are unique to this package.
- OrderBy
- OrderByDescending
- OrderByFunc
- ThenBy
- ThenByDescending
- Reverse
- Distinct
- DistinctBy
- Except
- ExceptBy
- Intersect
- IntersectBy
- Union
- UnionBy
- Where
- All
- Any
- Contains
- ContainsFunc
- Select
- SelectMany
- Zip
- Skip
- SkipLast
- SkipWhile
- Take
- TakeLast
- TakeWhile
- Chunk
- GroupJoin
- Join
- GroupBy
- DefaultIfEmpty
- Empty
- Range
- Repeat
- ElementAt
- ElementAtOrDefault
- First
- FirstOrDefault
- Last
- LastOrDefault
- Single
- SingleOrDefault
- FromMap
- FromSlice
- ToMap
- ToMapFunc
- ToSlice
- Concat
- Aggregate
- Average
- Count
- Max
- MaxBy
- MaxByFunc
- Min
- MinBy
- MinByFunc
- Sum
- Sumf
- ForEach
- Generator