forked from ahmetb/go-linq
-
Notifications
You must be signed in to change notification settings - Fork 0
/
example_test.go
2627 lines (2204 loc) · 60.4 KB
/
example_test.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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package linq
import (
"fmt"
"strings"
"time"
)
func ExampleKeyValue() {
m := make(map[int]bool)
m[10] = true
fmt.Println(From(m).Results())
// Output:
// [{10 true}]
}
func ExampleKeyValue_second() {
input := []KeyValue{
{10, true},
}
m := make(map[int]bool)
From(input).
ToMap(&m)
fmt.Println(m)
// Output:
// map[10:true]
}
// The following code example demonstrates how
// to use Range to generate a slice of values.
func ExampleRange() {
// Generate a slice of integers from 1 to 10
// and then select their squares.
var squares []int
Range(1, 10).
SelectT(
func(x int) int { return x * x },
).
ToSlice(&squares)
for _, num := range squares {
fmt.Println(num)
}
//Output:
//1
//4
//9
//16
//25
//36
//49
//64
//81
//100
}
// The following code example demonstrates how to use Repeat
// to generate a slice of a repeated value.
func ExampleRepeat() {
var slice []string
Repeat("I like programming.", 5).
ToSlice(&slice)
for _, str := range slice {
fmt.Println(str)
}
//Output:
//I like programming.
//I like programming.
//I like programming.
//I like programming.
//I like programming.
}
func ExampleQuery() {
query := From([]int{1, 2, 3, 4, 5}).Where(func(i interface{}) bool {
return i.(int) <= 3
})
next := query.Iterate()
for item, ok := next(); ok; item, ok = next() {
fmt.Println(item)
}
// Output:
// 1
// 2
// 3
}
// The following code example demonstrates how to use Aggregate function
func ExampleQuery_Aggregate() {
fruits := []string{"apple", "mango", "orange", "passionfruit", "grape"}
// Determine which string in the slice is the longest.
longestName := From(fruits).
Aggregate(
func(r interface{}, i interface{}) interface{} {
if len(r.(string)) > len(i.(string)) {
return r
}
return i
},
)
fmt.Println(longestName)
// Output:
// passionfruit
}
// The following code example demonstrates how to use AggregateWithSeed function
func ExampleQuery_AggregateWithSeed() {
ints := []int{4, 8, 8, 3, 9, 0, 7, 8, 2}
// Count the even numbers in the array, using a seed value of 0.
numEven := From(ints).
AggregateWithSeed(0,
func(total, next interface{}) interface{} {
if next.(int)%2 == 0 {
return total.(int) + 1
}
return total
},
)
fmt.Printf("The number of even integers is: %d", numEven)
// Output:
// The number of even integers is: 6
}
// The following code example demonstrates how to use AggregateWithSeedBy function
func ExampleQuery_AggregateWithSeedBy() {
input := []string{"apple", "mango", "orange", "passionfruit", "grape"}
// Determine whether any string in the array is longer than "banana".
longestName := From(input).
AggregateWithSeedBy("banana",
func(longest interface{}, next interface{}) interface{} {
if len(longest.(string)) > len(next.(string)) {
return longest
}
return next
},
// Return the final result
func(result interface{}) interface{} {
return fmt.Sprintf("The fruit with the longest name is %s.", result)
},
)
fmt.Println(longestName)
// Output:
// The fruit with the longest name is passionfruit.
}
// The following code example demonstrates how to
// use Distinct to return distinct elements from a slice of integers.
func ExampleOrderedQuery_Distinct() {
ages := []int{21, 46, 46, 55, 17, 21, 55, 55}
var distinctAges []int
From(ages).
OrderBy(
func(item interface{}) interface{} { return item },
).
Distinct().
ToSlice(&distinctAges)
fmt.Println(distinctAges)
// Output:
// [17 21 46 55]
}
// The following code example demonstrates how to
// use DistinctBy to return distinct elements from a ordered slice of elements.
func ExampleOrderedQuery_DistinctBy() {
type Product struct {
Name string
Code int
}
products := []Product{
{Name: "orange", Code: 4},
{Name: "apple", Code: 9},
{Name: "lemon", Code: 12},
{Name: "apple", Code: 9},
}
//Order and exclude duplicates.
var noduplicates []Product
From(products).
OrderBy(
func(item interface{}) interface{} { return item.(Product).Name },
).
DistinctBy(
func(item interface{}) interface{} { return item.(Product).Code },
).
ToSlice(&noduplicates)
for _, product := range noduplicates {
fmt.Printf("%s %d\n", product.Name, product.Code)
}
// Output:
// apple 9
// lemon 12
// orange 4
}
// The following code example demonstrates how to use ThenBy to perform
// a secondary ordering of the elements in a slice.
func ExampleOrderedQuery_ThenBy() {
fruits := []string{"grape", "passionfruit", "banana", "mango", "orange", "raspberry", "apple", "blueberry"}
// Sort the strings first by their length and then
//alphabetically by passing the identity selector function.
var query []string
From(fruits).
OrderBy(
func(fruit interface{}) interface{} { return len(fruit.(string)) },
).
ThenBy(
func(fruit interface{}) interface{} { return fruit },
).
ToSlice(&query)
for _, fruit := range query {
fmt.Println(fruit)
}
// Output:
// apple
// grape
// mango
// banana
// orange
// blueberry
// raspberry
// passionfruit
}
// The following code example demonstrates how to use All to determine
// whether all the elements in a slice satisfy a condition.
// Variable allStartWithB is true if all the pet names start with "B"
// or if the pets array is empty.
func ExampleQuery_All() {
type Pet struct {
Name string
Age int
}
pets := []Pet{
{Name: "Barley", Age: 10},
{Name: "Boots", Age: 4},
{Name: "Whiskers", Age: 6},
}
// Determine whether all pet names
// in the array start with 'B'.
allStartWithB := From(pets).
All(
func(pet interface{}) bool { return strings.HasPrefix(pet.(Pet).Name, "B") },
)
fmt.Printf("All pet names start with 'B'? %t", allStartWithB)
// Output:
//
// All pet names start with 'B'? false
}
// The following code example demonstrates how to use Any to determine
// whether a slice contains any elements.
func ExampleQuery_Any() {
numbers := []int{1, 2}
hasElements := From(numbers).Any()
fmt.Printf("Are there any element in the list? %t", hasElements)
// Output:
// Are there any element in the list? true
}
// The following code example demonstrates how to use AnyWith
// to determine whether any element in a slice satisfies a condition.
func ExampleQuery_AnyWith() {
type Pet struct {
Name string
Age int
Vaccinated bool
}
pets := []Pet{
{Name: "Barley", Age: 8, Vaccinated: true},
{Name: "Boots", Age: 4, Vaccinated: false},
{Name: "Whiskers", Age: 1, Vaccinated: false},
}
// Determine whether any pets over age 1 are also unvaccinated.
unvaccinated := From(pets).
AnyWith(
func(p interface{}) bool {
return p.(Pet).Age > 1 && p.(Pet).Vaccinated == false
},
)
fmt.Printf("Are there any unvaccinated animals over age one? %t", unvaccinated)
// Output:
//
// Are there any unvaccinated animals over age one? true
}
// The following code example demonstrates how to use Append
// to include an elements in the last position of a slice.
func ExampleQuery_Append() {
input := []int{1, 2, 3, 4}
q := From(input).Append(5)
last := q.Last()
fmt.Println(last)
// Output:
// 5
}
//The following code example demonstrates how to use Average
//to calculate the average of a slice of values.
func ExampleQuery_Average() {
grades := []int{78, 92, 100, 37, 81}
average := From(grades).Average()
fmt.Println(average)
// Output:
// 77.6
}
// The following code example demonstrates how to use Count
// to count the elements in an array.
func ExampleQuery_Count() {
fruits := []string{"apple", "banana", "mango", "orange", "passionfruit", "grape"}
numberOfFruits := From(fruits).Count()
fmt.Println(numberOfFruits)
// Output:
// 6
}
// The following code example demonstrates how to use Contains
// to determine whether a slice contains a specific element.
func ExampleQuery_Contains() {
slice := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
has5 := From(slice).Contains(5)
fmt.Printf("Does the slice contains 5? %t", has5)
// Output:
// Does the slice contains 5? true
}
//The following code example demonstrates how to use CountWith
//to count the even numbers in an array.
func ExampleQuery_CountWith() {
slice := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
evenCount := From(slice).
CountWith(
func(item interface{}) bool { return item.(int)%2 == 0 },
)
fmt.Println(evenCount)
// Output:
// 6
}
// The following example demonstrates how to use the DefaultIfEmpty
// method on the results of a group join to perform a left outer join.
//
// The first step in producing a left outer join of two collections is to perform
// an inner join by using a group join. In this example, the list of Person objects
// is inner-joined to the list of Pet objects based on a Person object that matches Pet.Owner.
//
// The second step is to include each element of the first (left) collection in the
// result set even if that element has no matches in the right collection.
// This is accomplished by calling DefaultIfEmpty on each sequence of matching
// elements from the group join.
// In this example, DefaultIfEmpty is called on each sequence of matching Pet elements.
// The method returns a collection that contains a single, default value if the sequence
// of matching Pet elements is empty for any Person element, thereby ensuring that each
// Person element is represented in the result collection.
func ExampleQuery_DefaultIfEmpty() {
type Person struct {
FirstName string
LastName string
}
type Pet struct {
Name string
Owner Person
}
magnus := Person{FirstName: "Magnus", LastName: "Hedlund"}
terry := Person{FirstName: "Terry", LastName: "Adams"}
charlotte := Person{FirstName: "Charlotte", LastName: "Weiss"}
arlene := Person{FirstName: "Arlene", LastName: "Huff"}
barley := Pet{Name: "Barley", Owner: terry}
boots := Pet{Name: "Boots", Owner: terry}
whiskers := Pet{Name: "Whiskers", Owner: charlotte}
bluemoon := Pet{Name: "Blue Moon", Owner: terry}
daisy := Pet{Name: "Daisy", Owner: magnus}
// Create two lists.
people := []Person{magnus, terry, charlotte, arlene}
pets := []Pet{barley, boots, whiskers, bluemoon, daisy}
results := []string{}
From(people).
GroupJoinT(
From(pets),
func(person Person) Person { return person },
func(pet Pet) Person { return pet.Owner },
func(person Person, pets []Pet) Group { return Group{Key: person, Group: From(pets).Results()} },
).
SelectManyByT(
func(g Group) Query { return From(g.Group).DefaultIfEmpty(Pet{}) },
func(pet Pet, group Group) string {
return fmt.Sprintf("%s: %s", group.Key.(Person).FirstName, pet.Name)
},
).
ToSlice(&results)
for _, s := range results {
fmt.Println(s)
}
// Output:
// Magnus: Daisy
// Terry: Barley
// Terry: Boots
// Terry: Blue Moon
// Charlotte: Whiskers
// Arlene:
}
//The following code example demonstrates how to use Distinct
//to return distinct elements from a slice of integers.
func ExampleQuery_Distinct() {
ages := []int{21, 46, 46, 55, 17, 21, 55, 55}
var distinctAges []int
From(ages).
Distinct().
ToSlice(&distinctAges)
fmt.Println(distinctAges)
// Output:
// [21 46 55 17]
}
// The following code example demonstrates how to
// use DistinctBy to return distinct elements from a ordered slice of elements.
func ExampleQuery_DistinctBy() {
type Product struct {
Name string
Code int
}
products := []Product{
{Name: "orange", Code: 4},
{Name: "apple", Code: 9},
{Name: "lemon", Code: 12},
{Name: "apple", Code: 9},
}
//Order and exclude duplicates.
var noduplicates []Product
From(products).
DistinctBy(
func(item interface{}) interface{} { return item.(Product).Code },
).
ToSlice(&noduplicates)
for _, product := range noduplicates {
fmt.Printf("%s %d\n", product.Name, product.Code)
}
// Output:
// orange 4
// apple 9
// lemon 12
}
// The following code example demonstrates how to use the Except
// method to compare two slices of numbers and return elements
// that appear only in the first slice.
func ExampleQuery_Except() {
numbers1 := []float32{2.0, 2.1, 2.2, 2.3, 2.4, 2.5}
numbers2 := []float32{2.2}
var onlyInFirstSet []float32
From(numbers1).
Except(From(numbers2)).
ToSlice(&onlyInFirstSet)
for _, number := range onlyInFirstSet {
fmt.Println(number)
}
// Output:
//2
//2.1
//2.3
//2.4
//2.5
}
// The following code example demonstrates how to use the Except
// method to compare two slices of numbers and return elements
// that appear only in the first slice.
func ExampleQuery_ExceptBy() {
type Product struct {
Name string
Code int
}
fruits1 := []Product{
{Name: "orange", Code: 4},
{Name: "apple", Code: 9},
{Name: "lemon", Code: 12},
{Name: "apple", Code: 9},
}
fruits2 := []Product{
{Name: "apple", Code: 9},
}
//Order and exclude duplicates.
var except []Product
From(fruits1).
ExceptBy(From(fruits2),
func(item interface{}) interface{} { return item.(Product).Code },
).
ToSlice(&except)
for _, product := range except {
fmt.Printf("%s %d\n", product.Name, product.Code)
}
// Output:
// orange 4
// lemon 12
}
// The following code example demonstrates how to use First
// to return the first element of an array.
func ExampleQuery_First() {
numbers := []int{9, 34, 65, 92, 87, 435, 3, 54, 83, 23, 87, 435, 67, 12, 19}
first := From(numbers).First()
fmt.Println(first)
// Output:
// 9
}
//The following code example demonstrates how to use FirstWith
// to return the first element of an array that satisfies a condition.
func ExampleQuery_FirstWith() {
numbers := []int{9, 34, 65, 92, 87, 435, 3, 54, 83, 23, 87, 435, 67, 12, 19}
first := From(numbers).
FirstWith(
func(item interface{}) bool { return item.(int) > 80 },
)
fmt.Println(first)
// Output:
// 92
}
//The following code example demonstrates how to use Intersect
//to return the elements that appear in each of two slices of integers.
func ExampleQuery_Intersect() {
id1 := []int{44, 26, 92, 30, 71, 38}
id2 := []int{39, 59, 83, 47, 26, 4, 30}
var both []int
From(id1).
Intersect(From(id2)).
ToSlice(&both)
for _, id := range both {
fmt.Println(id)
}
// Output:
// 26
// 30
}
//The following code example demonstrates how to use IntersectBy
//to return the elements that appear in each of two slices of products with same Code.
func ExampleQuery_IntersectBy() {
type Product struct {
Name string
Code int
}
store1 := []Product{
{Name: "orange", Code: 4},
{Name: "apple", Code: 9},
}
store2 := []Product{
{Name: "lemon", Code: 12},
{Name: "apple", Code: 9},
}
var duplicates []Product
From(store1).
IntersectBy(From(store2),
func(p interface{}) interface{} { return p.(Product).Code },
).
ToSlice(&duplicates)
for _, p := range duplicates {
fmt.Println(p.Name, "", p.Code)
}
// Output:
// apple 9
}
// The following code example demonstrates how to use Last
// to return the last element of an array.
func ExampleQuery_Last() {
numbers := []int{9, 34, 65, 92, 87, 435, 3, 54,
83, 23, 87, 67, 12, 19}
last := From(numbers).Last()
fmt.Println(last)
//Output:
//19
}
// The following code example demonstrates how to use LastWith
// to return the last element of an array.
func ExampleQuery_LastWith() {
numbers := []int{9, 34, 65, 92, 87, 435, 3, 54,
83, 23, 87, 67, 12, 19}
last := From(numbers).
LastWith(
func(n interface{}) bool { return n.(int) > 80 },
)
fmt.Println(last)
//Output:
//87
}
// The following code example demonstrates how to use Max
// to determine the maximum value in a slice.
func ExampleQuery_Max() {
numbers := []int64{4294967296, 466855135, 81125}
last := From(numbers).Max()
fmt.Println(last)
//Output:
//4294967296
}
// The following code example demonstrates how to use Min
// to determine the minimum value in a slice.
func ExampleQuery_Min() {
grades := []int{78, 92, 99, 37, 81}
min := From(grades).Min()
fmt.Println(min)
//Output:
//37
}
// The following code example demonstrates how to use OrderByDescending
// to sort the elements of a slice in descending order by using a selector function
func ExampleQuery_OrderByDescending() {
names := []string{"Ned", "Ben", "Susan"}
var result []string
From(names).
OrderByDescending(
func(n interface{}) interface{} { return n },
).ToSlice(&result)
fmt.Println(result)
// Output:
// [Susan Ned Ben]
}
// The following code example demonstrates how to use ThenByDescending to perform
// a secondary ordering of the elements in a slice in descending order.
func ExampleOrderedQuery_ThenByDescending() {
fruits := []string{"apPLe", "baNanA", "apple", "APple", "orange", "BAnana", "ORANGE", "apPLE"}
// Sort the strings first ascending by their length and
// then descending using a custom case insensitive comparer.
var query []string
From(fruits).
OrderBy(
func(fruit interface{}) interface{} { return len(fruit.(string)) },
).
ThenByDescending(
func(fruit interface{}) interface{} { return fruit.(string)[0] },
).
ToSlice(&query)
for _, fruit := range query {
fmt.Println(fruit)
}
// Output:
// apPLe
// apPLE
// apple
// APple
// orange
// baNanA
// ORANGE
// BAnana
}
// The following code example demonstrates how to use Concat
// to concatenate two slices.
func ExampleQuery_Concat() {
q := From([]int{1, 2, 3}).
Concat(From([]int{4, 5, 6}))
fmt.Println(q.Results())
// Output:
// [1 2 3 4 5 6]
}
func ExampleQuery_GroupBy() {
input := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
q := From(input).GroupBy(
func(i interface{}) interface{} { return i.(int) % 2 },
func(i interface{}) interface{} { return i.(int) })
fmt.Println(q.OrderBy(func(i interface{}) interface{} {
return i.(Group).Key
}).Results())
// Output:
// [{0 [2 4 6 8]} {1 [1 3 5 7 9]}]
}
// The following code example demonstrates how to use GroupJoin
// to perform a grouped join on two slices
func ExampleQuery_GroupJoin() {
fruits := []string{
"apple",
"banana",
"apricot",
"cherry",
"clementine",
}
q := FromString("abc").
GroupJoin(From(fruits),
func(i interface{}) interface{} { return i },
func(i interface{}) interface{} { return []rune(i.(string))[0] },
func(outer interface{}, inners []interface{}) interface{} {
return KeyValue{string(outer.(rune)), inners}
},
)
fmt.Println(q.Results())
// Output:
// [{a [apple apricot]} {b [banana]} {c [cherry clementine]}]
}
// The following code example demonstrates how to use IndexOf
// to retrieve the position of an item in the array and then
// update that item.
func ExampleQuery_IndexOf() {
type Item struct {
ID uint64
Name string
}
items := []Item{
{
ID: 1,
Name: "Joe",
},
{
ID: 2,
Name: "Bob",
},
{
ID: 3,
Name: "Rickster",
},
{
ID: 4,
Name: "Jim",
},
}
index := From(items).IndexOf(func(i interface{}) bool {
item, ok := i.(Item)
return ok && item.Name == "Rickster"
})
if index >= 0 {
// We found the item in the array. Change the name using the index.
items[index].Name = "Joshua"
fmt.Println("Item found at:", index, "new name:", items[index].Name)
}
// Output:
// Item found at: 2 new name: Joshua
}
// The following code example demonstrates how to use Join
// to perform an inner join of two slices based on a common key.
func ExampleQuery_Join() {
fruits := []string{
"apple",
"banana",
"apricot",
"cherry",
"clementine",
}
q := Range(1, 10).
Join(From(fruits),
func(i interface{}) interface{} { return i },
func(i interface{}) interface{} { return len(i.(string)) },
func(outer interface{}, inner interface{}) interface{} {
return KeyValue{outer, inner}
},
)
fmt.Println(q.Results())
// Output:
// [{5 apple} {6 banana} {6 cherry} {7 apricot} {10 clementine}]
}
// The following code example demonstrates how to use OrderBy
// to sort the elements of a slice.
func ExampleQuery_OrderBy() {
q := Range(1, 10).
OrderBy(
func(i interface{}) interface{} { return i.(int) % 2 },
).
ThenByDescending(
func(i interface{}) interface{} { return i },
)
fmt.Println(q.Results())
// Output:
// [10 8 6 4 2 9 7 5 3 1]
}
// The following code example demonstrates how to use Prepend
// to include an elements in the first position of a slice.
func ExampleQuery_Prepend() {
input := []int{2, 3, 4, 5}
q := From(input).Prepend(1)
first := q.First()
fmt.Println(first)
// Output:
// 1
}
// The following code example demonstrates how to use Reverse
// to reverse the order of elements in a string.
func ExampleQuery_Reverse() {
input := "apple"
var output []rune
From(input).
Reverse().
ToSlice(&output)
fmt.Println(string(output))
// Output:
// elppa
}
// The following code example demonstrates how to use Select
// to project over a slice of values.
func ExampleQuery_Select() {
squares := []int{}
Range(1, 10).
Select(
func(x interface{}) interface{} { return x.(int) * x.(int) },
).
ToSlice(&squares)
fmt.Println(squares)
// Output:
// [1 4 9 16 25 36 49 64 81 100]
}
func ExampleQuery_SelectMany() {
input := [][]int{{1, 2, 3}, {4, 5, 6, 7}}
q := From(input).
SelectMany(
func(i interface{}) Query { return From(i) },
)
fmt.Println(q.Results())
// Output:
// [1 2 3 4 5 6 7]
}
// The following code example demonstrates how to use Select
// to project over a slice of values and use the index of each element.
func ExampleQuery_SelectIndexed() {
fruits := []string{"apple", "banana", "mango", "orange", "passionfruit", "grape"}
result := []string{}
From(fruits).
SelectIndexed(
func(index int, fruit interface{}) interface{} { return fruit.(string)[:index] },
).
ToSlice(&result)
fmt.Println(result)
// Output:
// [ b ma ora pass grape]
}
// The following code example demonstrates how to use SelectManyByIndexed
// to perform a one-to-many projection over an array and use the index of each outer element.
func ExampleQuery_SelectManyByIndexed() {
type Pet struct {
Name string
}
type Person struct {
Name string
Pets []Pet
}
magnus := Person{
Name: "Hedlund, Magnus",
Pets: []Pet{{Name: "Daisy"}},
}
terry := Person{
Name: "Adams, Terry",
Pets: []Pet{{Name: "Barley"}, {Name: "Boots"}},
}
charlotte := Person{
Name: "Weiss, Charlotte",
Pets: []Pet{{Name: "Whiskers"}},
}
people := []Person{magnus, terry, charlotte}
var results []string
From(people).
SelectManyByIndexed(
func(index int, person interface{}) Query {
return From(person.(Person).Pets).
Select(func(pet interface{}) interface{} {
return fmt.Sprintf("%d - %s", index, pet.(Pet).Name)
})
},
func(indexedPet, person interface{}) interface{} {
return fmt.Sprintf("Pet: %s, Owner: %s", indexedPet, person.(Person).Name)
},
).
ToSlice(&results)
for _, result := range results {
fmt.Println(result)
}