-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
single.go
41 lines (39 loc) · 994 Bytes
/
single.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package linq
// Single returns the only element of a sequence, and return an error InvalidOperation if more than one such element exists.
func Single[T any, E IEnumerable[T]](src E) (def T, _ error) {
e := src()
v, err := e.Next()
if err != nil {
if isEOC(err) {
err = InvalidOperation
}
return def, err
}
_, err = e.Next()
if err == nil {
return def, InvalidOperation
}
if !isEOC(err) {
return def, err
}
return v, nil
}
// 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 SingleOrDefault[T any, E IEnumerable[T]](src E, defaultValue T) (def T, _ error) {
e := src()
v, err := e.Next()
if err != nil {
if isEOC(err) {
return defaultValue, nil
}
return def, err
}
_, err = e.Next()
if err == nil {
return def, InvalidOperation
}
if !isEOC(err) {
return def, err
}
return v, nil
}