diff --git a/README.md b/README.md index 14c22e1..e903921 100644 --- a/README.md +++ b/README.md @@ -47,10 +47,24 @@ func main() { 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 { + // 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) + } } ``` @@ -60,6 +74,11 @@ Output: 425 山路 信之 405 緒方 俊 136 星 雅彦 +---- +594 三宅 直人 +425 山路 信之 +405 緒方 俊 +136 星 雅彦 ``` ## Functions diff --git a/iter.go b/iter.go new file mode 100644 index 0000000..96ae0ad --- /dev/null +++ b/iter.go @@ -0,0 +1,34 @@ +//go:build go1.23 + +package linq + +import "iter" + +func (e Enumerable[T]) All() iter.Seq2[T, error] { + return iterAll(e()) +} + +func (e OrderedEnumerable[T]) All() iter.Seq2[T, error] { + return iterAll(e()) +} + +func iterAll[T any, E Enumerator[T]](e E) iter.Seq2[T, error] { + return func(yield func(T, error) bool) { + for { + v, err := e.Next() + if err != nil { + if isEOC(err) { + return + } + } + + if !yield(v, err) { + return + } + + if err != nil { + return + } + } + } +} diff --git a/iter_test.go b/iter_test.go new file mode 100644 index 0000000..715b6c5 --- /dev/null +++ b/iter_test.go @@ -0,0 +1,25 @@ +//go:build go1.23 + +package linq_test + +import ( + "testing" + + "github.com/makiuchi-d/linq/v2" +) + +func TestIterAll(t *testing.T) { + src := linq.FromSlice([]int{1, 2, 3, 4, 5}) + c := 0 + s := 0 + for n, err := range src.All() { + if err != nil { + t.Fatalf("%v", err) + } + c++ + s += n + } + if c != 5 || s != 15 { + t.Fatalf("(c, s) = (%v, %v) wants (%v, %v)", c, s, 5, 15) + } +}