example_test.go 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627
  1. package help
  2. import (
  3. "fmt"
  4. "strings"
  5. "time"
  6. )
  7. func ExampleKeyValue() {
  8. m := make(map[int]bool)
  9. m[10] = true
  10. fmt.Println(From(m).Results())
  11. // Output:
  12. // [{10 true}]
  13. }
  14. func ExampleKeyValue_second() {
  15. input := []KeyValue{
  16. {10, true},
  17. }
  18. m := make(map[int]bool)
  19. From(input).
  20. ToMap(&m)
  21. fmt.Println(m)
  22. // Output:
  23. // map[10:true]
  24. }
  25. // The following code example demonstrates how
  26. // to use Range to generate a slice of values.
  27. func ExampleRange() {
  28. // Generate a slice of integers from 1 to 10
  29. // and then select their squares.
  30. var squares []int
  31. Range(1, 10).
  32. SelectT(
  33. func(x int) int { return x * x },
  34. ).
  35. ToSlice(&squares)
  36. for _, num := range squares {
  37. fmt.Println(num)
  38. }
  39. //Output:
  40. //1
  41. //4
  42. //9
  43. //16
  44. //25
  45. //36
  46. //49
  47. //64
  48. //81
  49. //100
  50. }
  51. // The following code example demonstrates how to use Repeat
  52. // to generate a slice of a repeated value.
  53. func ExampleRepeat() {
  54. var slice []string
  55. Repeat("I like programming.", 5).
  56. ToSlice(&slice)
  57. for _, str := range slice {
  58. fmt.Println(str)
  59. }
  60. //Output:
  61. //I like programming.
  62. //I like programming.
  63. //I like programming.
  64. //I like programming.
  65. //I like programming.
  66. }
  67. func ExampleQuery() {
  68. query := From([]int{1, 2, 3, 4, 5}).Where(func(i interface{}) bool {
  69. return i.(int) <= 3
  70. })
  71. next := query.Iterate()
  72. for item, ok := next(); ok; item, ok = next() {
  73. fmt.Println(item)
  74. }
  75. // Output:
  76. // 1
  77. // 2
  78. // 3
  79. }
  80. // The following code example demonstrates how to use Aggregate function
  81. func ExampleQuery_Aggregate() {
  82. fruits := []string{"apple", "mango", "orange", "passionfruit", "grape"}
  83. // Determine which string in the slice is the longest.
  84. longestName := From(fruits).
  85. Aggregate(
  86. func(r interface{}, i interface{}) interface{} {
  87. if len(r.(string)) > len(i.(string)) {
  88. return r
  89. }
  90. return i
  91. },
  92. )
  93. fmt.Println(longestName)
  94. // Output:
  95. // passionfruit
  96. }
  97. // The following code example demonstrates how to use AggregateWithSeed function
  98. func ExampleQuery_AggregateWithSeed() {
  99. ints := []int{4, 8, 8, 3, 9, 0, 7, 8, 2}
  100. // Count the even numbers in the array, using a seed value of 0.
  101. numEven := From(ints).
  102. AggregateWithSeed(0,
  103. func(total, next interface{}) interface{} {
  104. if next.(int)%2 == 0 {
  105. return total.(int) + 1
  106. }
  107. return total
  108. },
  109. )
  110. fmt.Printf("The number of even integers is: %d", numEven)
  111. // Output:
  112. // The number of even integers is: 6
  113. }
  114. // The following code example demonstrates how to use AggregateWithSeedBy function
  115. func ExampleQuery_AggregateWithSeedBy() {
  116. input := []string{"apple", "mango", "orange", "passionfruit", "grape"}
  117. // Determine whether any string in the array is longer than "banana".
  118. longestName := From(input).
  119. AggregateWithSeedBy("banana",
  120. func(longest interface{}, next interface{}) interface{} {
  121. if len(longest.(string)) > len(next.(string)) {
  122. return longest
  123. }
  124. return next
  125. },
  126. // Return the final result
  127. func(result interface{}) interface{} {
  128. return fmt.Sprintf("The fruit with the longest name is %s.", result)
  129. },
  130. )
  131. fmt.Println(longestName)
  132. // Output:
  133. // The fruit with the longest name is passionfruit.
  134. }
  135. // The following code example demonstrates how to
  136. // use Distinct to return distinct elements from a slice of integers.
  137. func ExampleOrderedQuery_Distinct() {
  138. ages := []int{21, 46, 46, 55, 17, 21, 55, 55}
  139. var distinctAges []int
  140. From(ages).
  141. OrderBy(
  142. func(item interface{}) interface{} { return item },
  143. ).
  144. Distinct().
  145. ToSlice(&distinctAges)
  146. fmt.Println(distinctAges)
  147. // Output:
  148. // [17 21 46 55]
  149. }
  150. // The following code example demonstrates how to
  151. // use DistinctBy to return distinct elements from a ordered slice of elements.
  152. func ExampleOrderedQuery_DistinctBy() {
  153. type Product struct {
  154. Name string
  155. Code int
  156. }
  157. products := []Product{
  158. {Name: "orange", Code: 4},
  159. {Name: "apple", Code: 9},
  160. {Name: "lemon", Code: 12},
  161. {Name: "apple", Code: 9},
  162. }
  163. //Order and exclude duplicates.
  164. var noduplicates []Product
  165. From(products).
  166. OrderBy(
  167. func(item interface{}) interface{} { return item.(Product).Name },
  168. ).
  169. DistinctBy(
  170. func(item interface{}) interface{} { return item.(Product).Code },
  171. ).
  172. ToSlice(&noduplicates)
  173. for _, product := range noduplicates {
  174. fmt.Printf("%s %d\n", product.Name, product.Code)
  175. }
  176. // Output:
  177. // apple 9
  178. // lemon 12
  179. // orange 4
  180. }
  181. // The following code example demonstrates how to use ThenBy to perform
  182. // a secondary ordering of the elements in a slice.
  183. func ExampleOrderedQuery_ThenBy() {
  184. fruits := []string{"grape", "passionfruit", "banana", "mango", "orange", "raspberry", "apple", "blueberry"}
  185. // Sort the strings first by their length and then
  186. //alphabetically by passing the identity selector function.
  187. var query []string
  188. From(fruits).
  189. OrderBy(
  190. func(fruit interface{}) interface{} { return len(fruit.(string)) },
  191. ).
  192. ThenBy(
  193. func(fruit interface{}) interface{} { return fruit },
  194. ).
  195. ToSlice(&query)
  196. for _, fruit := range query {
  197. fmt.Println(fruit)
  198. }
  199. // Output:
  200. // apple
  201. // grape
  202. // mango
  203. // banana
  204. // orange
  205. // blueberry
  206. // raspberry
  207. // passionfruit
  208. }
  209. // The following code example demonstrates how to use All to determine
  210. // whether all the elements in a slice satisfy a condition.
  211. // Variable allStartWithB is true if all the pet names start with "B"
  212. // or if the pets array is empty.
  213. func ExampleQuery_All() {
  214. type Pet struct {
  215. Name string
  216. Age int
  217. }
  218. pets := []Pet{
  219. {Name: "Barley", Age: 10},
  220. {Name: "Boots", Age: 4},
  221. {Name: "Whiskers", Age: 6},
  222. }
  223. // Determine whether all pet names
  224. // in the array start with 'B'.
  225. allStartWithB := From(pets).
  226. All(
  227. func(pet interface{}) bool { return strings.HasPrefix(pet.(Pet).Name, "B") },
  228. )
  229. fmt.Printf("All pet names start with 'B'? %t", allStartWithB)
  230. // Output:
  231. //
  232. // All pet names start with 'B'? false
  233. }
  234. // The following code example demonstrates how to use Any to determine
  235. // whether a slice contains any elements.
  236. func ExampleQuery_Any() {
  237. numbers := []int{1, 2}
  238. hasElements := From(numbers).Any()
  239. fmt.Printf("Are there any element in the list? %t", hasElements)
  240. // Output:
  241. // Are there any element in the list? true
  242. }
  243. // The following code example demonstrates how to use AnyWith
  244. // to determine whether any element in a slice satisfies a condition.
  245. func ExampleQuery_AnyWith() {
  246. type Pet struct {
  247. Name string
  248. Age int
  249. Vaccinated bool
  250. }
  251. pets := []Pet{
  252. {Name: "Barley", Age: 8, Vaccinated: true},
  253. {Name: "Boots", Age: 4, Vaccinated: false},
  254. {Name: "Whiskers", Age: 1, Vaccinated: false},
  255. }
  256. // Determine whether any pets over age 1 are also unvaccinated.
  257. unvaccinated := From(pets).
  258. AnyWith(
  259. func(p interface{}) bool {
  260. return p.(Pet).Age > 1 && p.(Pet).Vaccinated == false
  261. },
  262. )
  263. fmt.Printf("Are there any unvaccinated animals over age one? %t", unvaccinated)
  264. // Output:
  265. //
  266. // Are there any unvaccinated animals over age one? true
  267. }
  268. // The following code example demonstrates how to use Append
  269. // to include an elements in the last position of a slice.
  270. func ExampleQuery_Append() {
  271. input := []int{1, 2, 3, 4}
  272. q := From(input).Append(5)
  273. last := q.Last()
  274. fmt.Println(last)
  275. // Output:
  276. // 5
  277. }
  278. //The following code example demonstrates how to use Average
  279. //to calculate the average of a slice of values.
  280. func ExampleQuery_Average() {
  281. grades := []int{78, 92, 100, 37, 81}
  282. average := From(grades).Average()
  283. fmt.Println(average)
  284. // Output:
  285. // 77.6
  286. }
  287. // The following code example demonstrates how to use Count
  288. // to count the elements in an array.
  289. func ExampleQuery_Count() {
  290. fruits := []string{"apple", "banana", "mango", "orange", "passionfruit", "grape"}
  291. numberOfFruits := From(fruits).Count()
  292. fmt.Println(numberOfFruits)
  293. // Output:
  294. // 6
  295. }
  296. // The following code example demonstrates how to use Contains
  297. // to determine whether a slice contains a specific element.
  298. func ExampleQuery_Contains() {
  299. slice := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
  300. has5 := From(slice).Contains(5)
  301. fmt.Printf("Does the slice contains 5? %t", has5)
  302. // Output:
  303. // Does the slice contains 5? true
  304. }
  305. //The following code example demonstrates how to use CountWith
  306. //to count the even numbers in an array.
  307. func ExampleQuery_CountWith() {
  308. slice := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
  309. evenCount := From(slice).
  310. CountWith(
  311. func(item interface{}) bool { return item.(int)%2 == 0 },
  312. )
  313. fmt.Println(evenCount)
  314. // Output:
  315. // 6
  316. }
  317. // The following example demonstrates how to use the DefaultIfEmpty
  318. // method on the results of a group join to perform a left outer join.
  319. //
  320. // The first step in producing a left outer join of two collections is to perform
  321. // an inner join by using a group join. In this example, the list of Person objects
  322. // is inner-joined to the list of Pet objects based on a Person object that matches Pet.Owner.
  323. //
  324. // The second step is to include each element of the first (left) collection in the
  325. // result set even if that element has no matches in the right collection.
  326. // This is accomplished by calling DefaultIfEmpty on each sequence of matching
  327. // elements from the group join.
  328. // In this example, DefaultIfEmpty is called on each sequence of matching Pet elements.
  329. // The method returns a collection that contains a single, default value if the sequence
  330. // of matching Pet elements is empty for any Person element, thereby ensuring that each
  331. // Person element is represented in the result collection.
  332. func ExampleQuery_DefaultIfEmpty() {
  333. type Person struct {
  334. FirstName string
  335. LastName string
  336. }
  337. type Pet struct {
  338. Name string
  339. Owner Person
  340. }
  341. magnus := Person{FirstName: "Magnus", LastName: "Hedlund"}
  342. terry := Person{FirstName: "Terry", LastName: "Adams"}
  343. charlotte := Person{FirstName: "Charlotte", LastName: "Weiss"}
  344. arlene := Person{FirstName: "Arlene", LastName: "Huff"}
  345. barley := Pet{Name: "Barley", Owner: terry}
  346. boots := Pet{Name: "Boots", Owner: terry}
  347. whiskers := Pet{Name: "Whiskers", Owner: charlotte}
  348. bluemoon := Pet{Name: "Blue Moon", Owner: terry}
  349. daisy := Pet{Name: "Daisy", Owner: magnus}
  350. // Create two lists.
  351. people := []Person{magnus, terry, charlotte, arlene}
  352. pets := []Pet{barley, boots, whiskers, bluemoon, daisy}
  353. results := []string{}
  354. From(people).
  355. GroupJoinT(
  356. From(pets),
  357. func(person Person) Person { return person },
  358. func(pet Pet) Person { return pet.Owner },
  359. func(person Person, pets []Pet) Group { return Group{Key: person, Group: From(pets).Results()} },
  360. ).
  361. SelectManyByT(
  362. func(g Group) Query { return From(g.Group).DefaultIfEmpty(Pet{}) },
  363. func(pet Pet, group Group) string {
  364. return fmt.Sprintf("%s: %s", group.Key.(Person).FirstName, pet.Name)
  365. },
  366. ).
  367. ToSlice(&results)
  368. for _, s := range results {
  369. fmt.Println(s)
  370. }
  371. // Output:
  372. // Magnus: Daisy
  373. // Terry: Barley
  374. // Terry: Boots
  375. // Terry: Blue Moon
  376. // Charlotte: Whiskers
  377. // Arlene:
  378. }
  379. //The following code example demonstrates how to use Distinct
  380. //to return distinct elements from a slice of integers.
  381. func ExampleQuery_Distinct() {
  382. ages := []int{21, 46, 46, 55, 17, 21, 55, 55}
  383. var distinctAges []int
  384. From(ages).
  385. Distinct().
  386. ToSlice(&distinctAges)
  387. fmt.Println(distinctAges)
  388. // Output:
  389. // [21 46 55 17]
  390. }
  391. // The following code example demonstrates how to
  392. // use DistinctBy to return distinct elements from a ordered slice of elements.
  393. func ExampleQuery_DistinctBy() {
  394. type Product struct {
  395. Name string
  396. Code int
  397. }
  398. products := []Product{
  399. {Name: "orange", Code: 4},
  400. {Name: "apple", Code: 9},
  401. {Name: "lemon", Code: 12},
  402. {Name: "apple", Code: 9},
  403. }
  404. //Order and exclude duplicates.
  405. var noduplicates []Product
  406. From(products).
  407. DistinctBy(
  408. func(item interface{}) interface{} { return item.(Product).Code },
  409. ).
  410. ToSlice(&noduplicates)
  411. for _, product := range noduplicates {
  412. fmt.Printf("%s %d\n", product.Name, product.Code)
  413. }
  414. // Output:
  415. // orange 4
  416. // apple 9
  417. // lemon 12
  418. }
  419. // The following code example demonstrates how to use the Except
  420. // method to compare two slices of numbers and return elements
  421. // that appear only in the first slice.
  422. func ExampleQuery_Except() {
  423. numbers1 := []float32{2.0, 2.1, 2.2, 2.3, 2.4, 2.5}
  424. numbers2 := []float32{2.2}
  425. var onlyInFirstSet []float32
  426. From(numbers1).
  427. Except(From(numbers2)).
  428. ToSlice(&onlyInFirstSet)
  429. for _, number := range onlyInFirstSet {
  430. fmt.Println(number)
  431. }
  432. // Output:
  433. //2
  434. //2.1
  435. //2.3
  436. //2.4
  437. //2.5
  438. }
  439. // The following code example demonstrates how to use the Except
  440. // method to compare two slices of numbers and return elements
  441. // that appear only in the first slice.
  442. func ExampleQuery_ExceptBy() {
  443. type Product struct {
  444. Name string
  445. Code int
  446. }
  447. fruits1 := []Product{
  448. {Name: "orange", Code: 4},
  449. {Name: "apple", Code: 9},
  450. {Name: "lemon", Code: 12},
  451. {Name: "apple", Code: 9},
  452. }
  453. fruits2 := []Product{
  454. {Name: "apple", Code: 9},
  455. }
  456. //Order and exclude duplicates.
  457. var except []Product
  458. From(fruits1).
  459. ExceptBy(From(fruits2),
  460. func(item interface{}) interface{} { return item.(Product).Code },
  461. ).
  462. ToSlice(&except)
  463. for _, product := range except {
  464. fmt.Printf("%s %d\n", product.Name, product.Code)
  465. }
  466. // Output:
  467. // orange 4
  468. // lemon 12
  469. }
  470. // The following code example demonstrates how to use First
  471. // to return the first element of an array.
  472. func ExampleQuery_First() {
  473. numbers := []int{9, 34, 65, 92, 87, 435, 3, 54, 83, 23, 87, 435, 67, 12, 19}
  474. first := From(numbers).First()
  475. fmt.Println(first)
  476. // Output:
  477. // 9
  478. }
  479. //The following code example demonstrates how to use FirstWith
  480. // to return the first element of an array that satisfies a condition.
  481. func ExampleQuery_FirstWith() {
  482. numbers := []int{9, 34, 65, 92, 87, 435, 3, 54, 83, 23, 87, 435, 67, 12, 19}
  483. first := From(numbers).
  484. FirstWith(
  485. func(item interface{}) bool { return item.(int) > 80 },
  486. )
  487. fmt.Println(first)
  488. // Output:
  489. // 92
  490. }
  491. //The following code example demonstrates how to use Intersect
  492. //to return the elements that appear in each of two slices of integers.
  493. func ExampleQuery_Intersect() {
  494. id1 := []int{44, 26, 92, 30, 71, 38}
  495. id2 := []int{39, 59, 83, 47, 26, 4, 30}
  496. var both []int
  497. From(id1).
  498. Intersect(From(id2)).
  499. ToSlice(&both)
  500. for _, id := range both {
  501. fmt.Println(id)
  502. }
  503. // Output:
  504. // 26
  505. // 30
  506. }
  507. //The following code example demonstrates how to use IntersectBy
  508. //to return the elements that appear in each of two slices of products with same Code.
  509. func ExampleQuery_IntersectBy() {
  510. type Product struct {
  511. Name string
  512. Code int
  513. }
  514. store1 := []Product{
  515. {Name: "orange", Code: 4},
  516. {Name: "apple", Code: 9},
  517. }
  518. store2 := []Product{
  519. {Name: "lemon", Code: 12},
  520. {Name: "apple", Code: 9},
  521. }
  522. var duplicates []Product
  523. From(store1).
  524. IntersectBy(From(store2),
  525. func(p interface{}) interface{} { return p.(Product).Code },
  526. ).
  527. ToSlice(&duplicates)
  528. for _, p := range duplicates {
  529. fmt.Println(p.Name, "", p.Code)
  530. }
  531. // Output:
  532. // apple 9
  533. }
  534. // The following code example demonstrates how to use Last
  535. // to return the last element of an array.
  536. func ExampleQuery_Last() {
  537. numbers := []int{9, 34, 65, 92, 87, 435, 3, 54,
  538. 83, 23, 87, 67, 12, 19}
  539. last := From(numbers).Last()
  540. fmt.Println(last)
  541. //Output:
  542. //19
  543. }
  544. // The following code example demonstrates how to use LastWith
  545. // to return the last element of an array.
  546. func ExampleQuery_LastWith() {
  547. numbers := []int{9, 34, 65, 92, 87, 435, 3, 54,
  548. 83, 23, 87, 67, 12, 19}
  549. last := From(numbers).
  550. LastWith(
  551. func(n interface{}) bool { return n.(int) > 80 },
  552. )
  553. fmt.Println(last)
  554. //Output:
  555. //87
  556. }
  557. // The following code example demonstrates how to use Max
  558. // to determine the maximum value in a slice.
  559. func ExampleQuery_Max() {
  560. numbers := []int64{4294967296, 466855135, 81125}
  561. last := From(numbers).Max()
  562. fmt.Println(last)
  563. //Output:
  564. //4294967296
  565. }
  566. // The following code example demonstrates how to use Min
  567. // to determine the minimum value in a slice.
  568. func ExampleQuery_Min() {
  569. grades := []int{78, 92, 99, 37, 81}
  570. min := From(grades).Min()
  571. fmt.Println(min)
  572. //Output:
  573. //37
  574. }
  575. // The following code example demonstrates how to use OrderByDescending
  576. // to sort the elements of a slice in descending order by using a selector function
  577. func ExampleQuery_OrderByDescending() {
  578. names := []string{"Ned", "Ben", "Susan"}
  579. var result []string
  580. From(names).
  581. OrderByDescending(
  582. func(n interface{}) interface{} { return n },
  583. ).ToSlice(&result)
  584. fmt.Println(result)
  585. // Output:
  586. // [Susan Ned Ben]
  587. }
  588. // The following code example demonstrates how to use ThenByDescending to perform
  589. // a secondary ordering of the elements in a slice in descending order.
  590. func ExampleOrderedQuery_ThenByDescending() {
  591. fruits := []string{"apPLe", "baNanA", "apple", "APple", "orange", "BAnana", "ORANGE", "apPLE"}
  592. // Sort the strings first ascending by their length and
  593. // then descending using a custom case insensitive comparer.
  594. var query []string
  595. From(fruits).
  596. OrderBy(
  597. func(fruit interface{}) interface{} { return len(fruit.(string)) },
  598. ).
  599. ThenByDescending(
  600. func(fruit interface{}) interface{} { return fruit.(string)[0] },
  601. ).
  602. ToSlice(&query)
  603. for _, fruit := range query {
  604. fmt.Println(fruit)
  605. }
  606. // Output:
  607. // apPLe
  608. // apPLE
  609. // apple
  610. // APple
  611. // orange
  612. // baNanA
  613. // ORANGE
  614. // BAnana
  615. }
  616. // The following code example demonstrates how to use Concat
  617. // to concatenate two slices.
  618. func ExampleQuery_Concat() {
  619. q := From([]int{1, 2, 3}).
  620. Concat(From([]int{4, 5, 6}))
  621. fmt.Println(q.Results())
  622. // Output:
  623. // [1 2 3 4 5 6]
  624. }
  625. func ExampleQuery_GroupBy() {
  626. input := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
  627. q := From(input).GroupBy(
  628. func(i interface{}) interface{} { return i.(int) % 2 },
  629. func(i interface{}) interface{} { return i.(int) })
  630. fmt.Println(q.OrderBy(func(i interface{}) interface{} {
  631. return i.(Group).Key
  632. }).Results())
  633. // Output:
  634. // [{0 [2 4 6 8]} {1 [1 3 5 7 9]}]
  635. }
  636. // The following code example demonstrates how to use GroupJoin
  637. // to perform a grouped join on two slices
  638. func ExampleQuery_GroupJoin() {
  639. fruits := []string{
  640. "apple",
  641. "banana",
  642. "apricot",
  643. "cherry",
  644. "clementine",
  645. }
  646. q := FromString("abc").
  647. GroupJoin(From(fruits),
  648. func(i interface{}) interface{} { return i },
  649. func(i interface{}) interface{} { return []rune(i.(string))[0] },
  650. func(outer interface{}, inners []interface{}) interface{} {
  651. return KeyValue{string(outer.(rune)), inners}
  652. },
  653. )
  654. fmt.Println(q.Results())
  655. // Output:
  656. // [{a [apple apricot]} {b [banana]} {c [cherry clementine]}]
  657. }
  658. // The following code example demonstrates how to use IndexOf
  659. // to retrieve the position of an item in the array and then
  660. // update that item.
  661. func ExampleQuery_IndexOf() {
  662. type Item struct {
  663. ID uint64
  664. Name string
  665. }
  666. items := []Item{
  667. {
  668. ID: 1,
  669. Name: "Joe",
  670. },
  671. {
  672. ID: 2,
  673. Name: "Bob",
  674. },
  675. {
  676. ID: 3,
  677. Name: "Rickster",
  678. },
  679. {
  680. ID: 4,
  681. Name: "Jim",
  682. },
  683. }
  684. index := From(items).IndexOf(func(i interface{}) bool {
  685. item, ok := i.(Item)
  686. return ok && item.Name == "Rickster"
  687. })
  688. if index >= 0 {
  689. // We found the item in the array. Change the name using the index.
  690. items[index].Name = "Joshua"
  691. fmt.Println("Item found at:", index, "new name:", items[index].Name)
  692. }
  693. // Output:
  694. // Item found at: 2 new name: Joshua
  695. }
  696. // The following code example demonstrates how to use Join
  697. // to perform an inner join of two slices based on a common key.
  698. func ExampleQuery_Join() {
  699. fruits := []string{
  700. "apple",
  701. "banana",
  702. "apricot",
  703. "cherry",
  704. "clementine",
  705. }
  706. q := Range(1, 10).
  707. Join(From(fruits),
  708. func(i interface{}) interface{} { return i },
  709. func(i interface{}) interface{} { return len(i.(string)) },
  710. func(outer interface{}, inner interface{}) interface{} {
  711. return KeyValue{outer, inner}
  712. },
  713. )
  714. fmt.Println(q.Results())
  715. // Output:
  716. // [{5 apple} {6 banana} {6 cherry} {7 apricot} {10 clementine}]
  717. }
  718. // The following code example demonstrates how to use OrderBy
  719. // to sort the elements of a slice.
  720. func ExampleQuery_OrderBy() {
  721. q := Range(1, 10).
  722. OrderBy(
  723. func(i interface{}) interface{} { return i.(int) % 2 },
  724. ).
  725. ThenByDescending(
  726. func(i interface{}) interface{} { return i },
  727. )
  728. fmt.Println(q.Results())
  729. // Output:
  730. // [10 8 6 4 2 9 7 5 3 1]
  731. }
  732. // The following code example demonstrates how to use Prepend
  733. // to include an elements in the first position of a slice.
  734. func ExampleQuery_Prepend() {
  735. input := []int{2, 3, 4, 5}
  736. q := From(input).Prepend(1)
  737. first := q.First()
  738. fmt.Println(first)
  739. // Output:
  740. // 1
  741. }
  742. // The following code example demonstrates how to use Reverse
  743. // to reverse the order of elements in a string.
  744. func ExampleQuery_Reverse() {
  745. input := "apple"
  746. var output []rune
  747. From(input).
  748. Reverse().
  749. ToSlice(&output)
  750. fmt.Println(string(output))
  751. // Output:
  752. // elppa
  753. }
  754. // The following code example demonstrates how to use Select
  755. // to project over a slice of values.
  756. func ExampleQuery_Select() {
  757. squares := []int{}
  758. Range(1, 10).
  759. Select(
  760. func(x interface{}) interface{} { return x.(int) * x.(int) },
  761. ).
  762. ToSlice(&squares)
  763. fmt.Println(squares)
  764. // Output:
  765. // [1 4 9 16 25 36 49 64 81 100]
  766. }
  767. func ExampleQuery_SelectMany() {
  768. input := [][]int{{1, 2, 3}, {4, 5, 6, 7}}
  769. q := From(input).
  770. SelectMany(
  771. func(i interface{}) Query { return From(i) },
  772. )
  773. fmt.Println(q.Results())
  774. // Output:
  775. // [1 2 3 4 5 6 7]
  776. }
  777. // The following code example demonstrates how to use Select
  778. // to project over a slice of values and use the index of each element.
  779. func ExampleQuery_SelectIndexed() {
  780. fruits := []string{"apple", "banana", "mango", "orange", "passionfruit", "grape"}
  781. result := []string{}
  782. From(fruits).
  783. SelectIndexed(
  784. func(index int, fruit interface{}) interface{} { return fruit.(string)[:index] },
  785. ).
  786. ToSlice(&result)
  787. fmt.Println(result)
  788. // Output:
  789. // [ b ma ora pass grape]
  790. }
  791. // The following code example demonstrates how to use SelectManyByIndexed
  792. // to perform a one-to-many projection over an array and use the index of each outer element.
  793. func ExampleQuery_SelectManyByIndexed() {
  794. type Pet struct {
  795. Name string
  796. }
  797. type Person struct {
  798. Name string
  799. Pets []Pet
  800. }
  801. magnus := Person{
  802. Name: "Hedlund, Magnus",
  803. Pets: []Pet{{Name: "Daisy"}},
  804. }
  805. terry := Person{
  806. Name: "Adams, Terry",
  807. Pets: []Pet{{Name: "Barley"}, {Name: "Boots"}},
  808. }
  809. charlotte := Person{
  810. Name: "Weiss, Charlotte",
  811. Pets: []Pet{{Name: "Whiskers"}},
  812. }
  813. people := []Person{magnus, terry, charlotte}
  814. var results []string
  815. From(people).
  816. SelectManyByIndexed(
  817. func(index int, person interface{}) Query {
  818. return From(person.(Person).Pets).
  819. Select(func(pet interface{}) interface{} {
  820. return fmt.Sprintf("%d - %s", index, pet.(Pet).Name)
  821. })
  822. },
  823. func(indexedPet, person interface{}) interface{} {
  824. return fmt.Sprintf("Pet: %s, Owner: %s", indexedPet, person.(Person).Name)
  825. },
  826. ).
  827. ToSlice(&results)
  828. for _, result := range results {
  829. fmt.Println(result)
  830. }
  831. // Output:
  832. // Pet: 0 - Daisy, Owner: Hedlund, Magnus
  833. // Pet: 1 - Barley, Owner: Adams, Terry
  834. // Pet: 1 - Boots, Owner: Adams, Terry
  835. // Pet: 2 - Whiskers, Owner: Weiss, Charlotte
  836. }
  837. // The following code example demonstrates how to use SelectManyIndexed
  838. // to perform a one-to-many projection over an slice of log data and print out their contents.
  839. func ExampleQuery_SelectManyIndexed() {
  840. type LogFile struct {
  841. Name string
  842. Lines []string
  843. }
  844. file1 := LogFile{
  845. Name: "file1.log",
  846. Lines: []string{
  847. "INFO: 2013/11/05 18:11:01 main.go:44: Special Information",
  848. "WARNING: 2013/11/05 18:11:01 main.go:45: There is something you need to know about",
  849. "ERROR: 2013/11/05 18:11:01 main.go:46: Something has failed",
  850. },
  851. }
  852. file2 := LogFile{
  853. Name: "file2.log",
  854. Lines: []string{
  855. "INFO: 2013/11/05 18:11:01 main.go:46: Everything is ok",
  856. },
  857. }
  858. file3 := LogFile{
  859. Name: "file3.log",
  860. Lines: []string{
  861. "2013/11/05 18:42:26 Hello World",
  862. },
  863. }
  864. logFiles := []LogFile{file1, file2, file3}
  865. var results []string
  866. From(logFiles).
  867. SelectManyIndexedT(func(fileIndex int, file LogFile) Query {
  868. return From(file.Lines).
  869. SelectIndexedT(func(lineIndex int, line string) string {
  870. return fmt.Sprintf("File:[%d] - %s => line: %d - %s", fileIndex+1, file.Name, lineIndex+1, line)
  871. })
  872. }).
  873. ToSlice(&results)
  874. for _, result := range results {
  875. fmt.Println(result)
  876. }
  877. // Output:
  878. // File:[1] - file1.log => line: 1 - INFO: 2013/11/05 18:11:01 main.go:44: Special Information
  879. // File:[1] - file1.log => line: 2 - WARNING: 2013/11/05 18:11:01 main.go:45: There is something you need to know about
  880. // File:[1] - file1.log => line: 3 - ERROR: 2013/11/05 18:11:01 main.go:46: Something has failed
  881. // File:[2] - file2.log => line: 1 - INFO: 2013/11/05 18:11:01 main.go:46: Everything is ok
  882. // File:[3] - file3.log => line: 1 - 2013/11/05 18:42:26 Hello World
  883. }
  884. // The following code example demonstrates how to use SelectMany
  885. // to perform a one-to-many projection over a slice
  886. func ExampleQuery_SelectManyBy() {
  887. type Pet struct {
  888. Name string
  889. }
  890. type Person struct {
  891. Name string
  892. Pets []Pet
  893. }
  894. magnus := Person{
  895. Name: "Hedlund, Magnus",
  896. Pets: []Pet{{Name: "Daisy"}},
  897. }
  898. terry := Person{
  899. Name: "Adams, Terry",
  900. Pets: []Pet{{Name: "Barley"}, {Name: "Boots"}},
  901. }
  902. charlotte := Person{
  903. Name: "Weiss, Charlotte",
  904. Pets: []Pet{{Name: "Whiskers"}},
  905. }
  906. people := []Person{magnus, terry, charlotte}
  907. var results []string
  908. From(people).
  909. SelectManyBy(
  910. func(person interface{}) Query { return From(person.(Person).Pets) },
  911. func(pet, person interface{}) interface{} {
  912. return fmt.Sprintf("Owner: %s, Pet: %s", person.(Person).Name, pet.(Pet).Name)
  913. },
  914. ).
  915. ToSlice(&results)
  916. for _, result := range results {
  917. fmt.Println(result)
  918. }
  919. // Output:
  920. // Owner: Hedlund, Magnus, Pet: Daisy
  921. // Owner: Adams, Terry, Pet: Barley
  922. // Owner: Adams, Terry, Pet: Boots
  923. // Owner: Weiss, Charlotte, Pet: Whiskers
  924. }
  925. // The following code example demonstrates how to use SequenceEqual
  926. // to determine whether two slices are equal.
  927. func ExampleQuery_SequenceEqual() {
  928. type Pet struct {
  929. Name string
  930. Age int
  931. }
  932. pets1 := []Pet{
  933. {Name: "Barley", Age: 8},
  934. {Name: "Boots", Age: 4},
  935. {Name: "Whiskers", Age: 1},
  936. {Name: "Daisy", Age: 4},
  937. }
  938. pets2 := []Pet{
  939. {Name: "Barley", Age: 8},
  940. {Name: "Boots", Age: 4},
  941. {Name: "Whiskers", Age: 1},
  942. {Name: "Daisy", Age: 4},
  943. }
  944. equal := From(pets1).SequenceEqual(From(pets2))
  945. fmt.Printf("Are the lists equals? %t", equal)
  946. // Output:
  947. // Are the lists equals? true
  948. }
  949. // The following code example demonstrates how to use Single
  950. // to select the only element of a slice.
  951. func ExampleQuery_Single() {
  952. fruits1 := []string{"orange"}
  953. fruit1 := From(fruits1).Single()
  954. fmt.Println(fruit1)
  955. // Output:
  956. // orange
  957. }
  958. // The following code example demonstrates how to use SingleWith
  959. // to select the only element of a slice that satisfies a condition.
  960. func ExampleQuery_SingleWith() {
  961. fruits := []string{"apple", "banana", "mango", "orange", "passionfruit", "grape"}
  962. fruit := From(fruits).
  963. SingleWith(
  964. func(f interface{}) bool { return len(f.(string)) > 10 },
  965. )
  966. fmt.Println(fruit)
  967. // Output:
  968. // passionfruit
  969. }
  970. // The following code example demonstrates how to use Skip
  971. // to skip a specified number of elements in a sorted array
  972. // and return the remaining elements.
  973. func ExampleQuery_Skip() {
  974. grades := []int{59, 82, 70, 56, 92, 98, 85}
  975. var lowerGrades []int
  976. From(grades).
  977. OrderByDescending(
  978. func(g interface{}) interface{} { return g },
  979. ).
  980. Skip(3).
  981. ToSlice(&lowerGrades)
  982. //All grades except the top three are:
  983. fmt.Println(lowerGrades)
  984. // Output:
  985. // [82 70 59 56]
  986. }
  987. // The following code example demonstrates how to use SkipWhile
  988. // to skip elements of an array as long as a condition is true.
  989. func ExampleQuery_SkipWhile() {
  990. grades := []int{59, 82, 70, 56, 92, 98, 85}
  991. var lowerGrades []int
  992. From(grades).
  993. OrderByDescending(
  994. func(g interface{}) interface{} { return g },
  995. ).
  996. SkipWhile(
  997. func(g interface{}) bool { return g.(int) >= 80 },
  998. ).
  999. ToSlice(&lowerGrades)
  1000. // All grades below 80:
  1001. fmt.Println(lowerGrades)
  1002. // Output:
  1003. // [70 59 56]
  1004. }
  1005. // The following code example demonstrates how to use SkipWhileIndexed
  1006. // to skip elements of an array as long as a condition that depends
  1007. // on the element's index is true.
  1008. func ExampleQuery_SkipWhileIndexed() {
  1009. amounts := []int{5000, 2500, 9000, 8000, 6500, 4000, 1500, 5500}
  1010. var query []int
  1011. From(amounts).
  1012. SkipWhileIndexed(
  1013. func(index int, amount interface{}) bool { return amount.(int) > index*1000 },
  1014. ).
  1015. ToSlice(&query)
  1016. fmt.Println(query)
  1017. // Output:
  1018. // [4000 1500 5500]
  1019. }
  1020. // The following code example demonstrates how to use Sort
  1021. // to order elements of an slice.
  1022. func ExampleQuery_Sort() {
  1023. amounts := []int{5000, 2500, 9000, 8000, 6500, 4000, 1500, 5500}
  1024. var query []int
  1025. From(amounts).
  1026. Sort(
  1027. func(i interface{}, j interface{}) bool { return i.(int) < j.(int) },
  1028. ).
  1029. ToSlice(&query)
  1030. fmt.Println(query)
  1031. // Output:
  1032. // [1500 2500 4000 5000 5500 6500 8000 9000]
  1033. }
  1034. // The following code example demonstrates how to use SumFloats
  1035. // to sum the values of a slice.
  1036. func ExampleQuery_SumFloats() {
  1037. numbers := []float64{43.68, 1.25, 583.7, 6.5}
  1038. sum := From(numbers).SumFloats()
  1039. fmt.Printf("The sum of the numbers is %f.", sum)
  1040. // Output:
  1041. // The sum of the numbers is 635.130000.
  1042. }
  1043. // The following code example demonstrates how to use SumInts
  1044. // to sum the values of a slice.
  1045. func ExampleQuery_SumInts() {
  1046. numbers := []int{43, 1, 583, 6}
  1047. sum := From(numbers).SumInts()
  1048. fmt.Printf("The sum of the numbers is %d.", sum)
  1049. // Output:
  1050. // The sum of the numbers is 633.
  1051. }
  1052. // The following code example demonstrates how to use SumUInts
  1053. // to sum the values of a slice.
  1054. func ExampleQuery_SumUInts() {
  1055. numbers := []uint{43, 1, 583, 6}
  1056. sum := From(numbers).SumUInts()
  1057. fmt.Printf("The sum of the numbers is %d.", sum)
  1058. // Output:
  1059. // The sum of the numbers is 633.
  1060. }
  1061. // The following code example demonstrates how to use Take
  1062. // to return elements from the start of a slice.
  1063. func ExampleQuery_Take() {
  1064. grades := []int{59, 82, 70, 56, 92, 98, 85}
  1065. var topThreeGrades []int
  1066. From(grades).
  1067. OrderByDescending(
  1068. func(grade interface{}) interface{} { return grade },
  1069. ).
  1070. Take(3).
  1071. ToSlice(&topThreeGrades)
  1072. fmt.Printf("The top three grades are: %v", topThreeGrades)
  1073. // Output:
  1074. // The top three grades are: [98 92 85]
  1075. }
  1076. // The following code example demonstrates how to use TakeWhile
  1077. // to return elements from the start of a slice.
  1078. func ExampleQuery_TakeWhile() {
  1079. fruits := []string{"apple", "banana", "mango", "orange", "passionfruit", "grape"}
  1080. var query []string
  1081. From(fruits).
  1082. TakeWhile(
  1083. func(fruit interface{}) bool { return fruit.(string) != "orange" },
  1084. ).
  1085. ToSlice(&query)
  1086. fmt.Println(query)
  1087. // Output:
  1088. // [apple banana mango]
  1089. }
  1090. // The following code example demonstrates how to use TakeWhileIndexed
  1091. // to return elements from the start of a slice as long as
  1092. // a condition that uses the element's index is true.
  1093. func ExampleQuery_TakeWhileIndexed() {
  1094. fruits := []string{"apple", "passionfruit", "banana", "mango",
  1095. "orange", "blueberry", "grape", "strawberry"}
  1096. var query []string
  1097. From(fruits).
  1098. TakeWhileIndexed(
  1099. func(index int, fruit interface{}) bool { return len(fruit.(string)) >= index },
  1100. ).
  1101. ToSlice(&query)
  1102. fmt.Println(query)
  1103. // Output:
  1104. // [apple passionfruit banana mango orange blueberry]
  1105. }
  1106. // The following code example demonstrates how to use ToChannel
  1107. // to send a slice to a channel.
  1108. func ExampleQuery_ToChannel() {
  1109. c := make(chan interface{})
  1110. go func() {
  1111. Repeat(10, 3).ToChannel(c)
  1112. }()
  1113. for i := range c {
  1114. fmt.Println(i)
  1115. }
  1116. // Output:
  1117. // 10
  1118. // 10
  1119. // 10
  1120. }
  1121. // The following code example demonstrates how to use ToChannelT
  1122. // to send a slice to a typed channel.
  1123. func ExampleQuery_ToChannelT() {
  1124. c := make(chan string)
  1125. go Repeat("ten", 3).ToChannelT(c)
  1126. for i := range c {
  1127. fmt.Println(i)
  1128. }
  1129. // Output:
  1130. // ten
  1131. // ten
  1132. // ten
  1133. }
  1134. // The following code example demonstrates how to use ToMap to populate a map.
  1135. func ExampleQuery_ToMap() {
  1136. type Product struct {
  1137. Name string
  1138. Code int
  1139. }
  1140. products := []Product{
  1141. {Name: "orange", Code: 4},
  1142. {Name: "apple", Code: 9},
  1143. {Name: "lemon", Code: 12},
  1144. {Name: "apple", Code: 9},
  1145. }
  1146. map1 := map[int]string{}
  1147. From(products).
  1148. SelectT(
  1149. func(item Product) KeyValue { return KeyValue{Key: item.Code, Value: item.Name} },
  1150. ).
  1151. ToMap(&map1)
  1152. fmt.Println(map1[4])
  1153. fmt.Println(map1[9])
  1154. fmt.Println(map1[12])
  1155. // Output:
  1156. // orange
  1157. // apple
  1158. // lemon
  1159. }
  1160. // The following code example demonstrates how to use ToMapBy
  1161. // by using a key and value selectors to populate a map.
  1162. func ExampleQuery_ToMapBy() {
  1163. input := [][]interface{}{{1, true}}
  1164. result := make(map[int]bool)
  1165. From(input).
  1166. ToMapBy(&result,
  1167. func(i interface{}) interface{} {
  1168. return i.([]interface{})[0]
  1169. },
  1170. func(i interface{}) interface{} {
  1171. return i.([]interface{})[1]
  1172. },
  1173. )
  1174. fmt.Println(result)
  1175. // Output:
  1176. // map[1:true]
  1177. }
  1178. // The following code example demonstrates how to use ToSlice to populate a slice.
  1179. func ExampleQuery_ToSlice() {
  1180. var result []int
  1181. Range(1, 10).ToSlice(&result)
  1182. fmt.Println(result)
  1183. // Output:
  1184. // [1 2 3 4 5 6 7 8 9 10]
  1185. }
  1186. // The following code example demonstrates how to use Union
  1187. // to obtain the union of two slices of integers.
  1188. func ExampleQuery_Union() {
  1189. q := Range(1, 10).Union(Range(6, 10))
  1190. fmt.Println(q.Results())
  1191. // Output:
  1192. // [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15]
  1193. }
  1194. // The following code example demonstrates how to use Where
  1195. // to filter a slices.
  1196. func ExampleQuery_Where() {
  1197. fruits := []string{"apple", "passionfruit", "banana", "mango",
  1198. "orange", "blueberry", "grape", "strawberry"}
  1199. var query []string
  1200. From(fruits).
  1201. Where(
  1202. func(f interface{}) bool { return len(f.(string)) > 6 },
  1203. ).
  1204. ToSlice(&query)
  1205. fmt.Println(query)
  1206. // Output:
  1207. // [passionfruit blueberry strawberry]
  1208. }
  1209. // The following code example demonstrates how to use WhereIndexed
  1210. // to filter a slice based on a predicate that involves the index of each element.
  1211. func ExampleQuery_WhereIndexed() {
  1212. numbers := []int{0, 30, 20, 15, 90, 85, 40, 75}
  1213. var query []int
  1214. From(numbers).
  1215. WhereIndexed(
  1216. func(index int, number interface{}) bool { return number.(int) <= index*10 },
  1217. ).
  1218. ToSlice(&query)
  1219. fmt.Println(query)
  1220. // Output:
  1221. // [0 20 15 40]
  1222. }
  1223. // The following code example demonstrates how to use the Zip
  1224. // method to merge two slices.
  1225. func ExampleQuery_Zip() {
  1226. number := []int{1, 2, 3, 4, 5}
  1227. words := []string{"one", "two", "three"}
  1228. q := From(number).
  1229. Zip(From(words),
  1230. func(a interface{}, b interface{}) interface{} { return []interface{}{a, b} },
  1231. )
  1232. fmt.Println(q.Results())
  1233. // Output:
  1234. // [[1 one] [2 two] [3 three]]
  1235. }
  1236. // The following code example demonstrates how to use ThenByDescendingT to perform
  1237. // a order in a slice of dates by year, and then by month descending.
  1238. func ExampleOrderedQuery_ThenByDescendingT() {
  1239. dates := []time.Time{
  1240. time.Date(2015, 3, 23, 0, 0, 0, 0, time.Local),
  1241. time.Date(2014, 7, 11, 0, 0, 0, 0, time.Local),
  1242. time.Date(2013, 5, 4, 0, 0, 0, 0, time.Local),
  1243. time.Date(2015, 1, 2, 0, 0, 0, 0, time.Local),
  1244. time.Date(2015, 7, 10, 0, 0, 0, 0, time.Local),
  1245. }
  1246. var orderedDates []time.Time
  1247. From(dates).
  1248. OrderByT(
  1249. func(date time.Time) int {
  1250. return date.Year()
  1251. }).
  1252. ThenByDescendingT(
  1253. func(date time.Time) int { return int(date.Month()) },
  1254. ).
  1255. ToSlice(&orderedDates)
  1256. for _, date := range orderedDates {
  1257. fmt.Println(date.Format("2006-Jan-02"))
  1258. }
  1259. // Output:
  1260. // 2013-May-04
  1261. // 2014-Jul-11
  1262. // 2015-Jul-10
  1263. // 2015-Mar-23
  1264. // 2015-Jan-02
  1265. }
  1266. // The following code example demonstrates how to use ThenByT to perform
  1267. // a orders in a slice of dates by year, and then by day.
  1268. func ExampleOrderedQuery_ThenByT() {
  1269. dates := []time.Time{
  1270. time.Date(2015, 3, 23, 0, 0, 0, 0, time.Local),
  1271. time.Date(2014, 7, 11, 0, 0, 0, 0, time.Local),
  1272. time.Date(2013, 5, 4, 0, 0, 0, 0, time.Local),
  1273. time.Date(2015, 1, 2, 0, 0, 0, 0, time.Local),
  1274. time.Date(2015, 7, 10, 0, 0, 0, 0, time.Local),
  1275. }
  1276. var orderedDates []time.Time
  1277. From(dates).
  1278. OrderByT(
  1279. func(date time.Time) int { return date.Year() },
  1280. ).
  1281. ThenByT(
  1282. func(date time.Time) int { return int(date.Day()) },
  1283. ).
  1284. ToSlice(&orderedDates)
  1285. for _, date := range orderedDates {
  1286. fmt.Println(date.Format("2006-Jan-02"))
  1287. }
  1288. // Output:
  1289. // 2013-May-04
  1290. // 2014-Jul-11
  1291. // 2015-Jan-02
  1292. // 2015-Jul-10
  1293. // 2015-Mar-23
  1294. }
  1295. // The following code example demonstrates how to reverse
  1296. // the order of words in a string using AggregateT.
  1297. func ExampleQuery_AggregateT() {
  1298. sentence := "the quick brown fox jumps over the lazy dog"
  1299. // Split the string into individual words.
  1300. words := strings.Split(sentence, " ")
  1301. // Prepend each word to the beginning of the
  1302. // new sentence to reverse the word order.
  1303. reversed := From(words).AggregateT(
  1304. func(workingSentence string, next string) string { return next + " " + workingSentence },
  1305. )
  1306. fmt.Println(reversed)
  1307. // Output:
  1308. // dog lazy the over jumps fox brown quick the
  1309. }
  1310. // The following code example demonstrates how to use AggregateWithSeed function
  1311. func ExampleQuery_AggregateWithSeedT() {
  1312. fruits := []string{"apple", "mango", "orange", "passionfruit", "grape"}
  1313. // Determine whether any string in the array is longer than "banana".
  1314. longestName := From(fruits).
  1315. AggregateWithSeedT("banana",
  1316. func(longest, next string) string {
  1317. if len(next) > len(longest) {
  1318. return next
  1319. }
  1320. return longest
  1321. },
  1322. )
  1323. fmt.Printf("The fruit with the longest name is %s.", longestName)
  1324. // Output:
  1325. // The fruit with the longest name is passionfruit.
  1326. }
  1327. // The following code example demonstrates how to use AggregateWithSeedByT function
  1328. func ExampleQuery_AggregateWithSeedByT() {
  1329. input := []string{"apple", "mango", "orange", "passionfruit", "grape"}
  1330. // Determine whether any string in the array is longer than "banana".
  1331. longestName := From(input).AggregateWithSeedByT("banana",
  1332. func(longest string, next string) string {
  1333. if len(longest) > len(next) {
  1334. return longest
  1335. }
  1336. return next
  1337. },
  1338. // Return the final result
  1339. func(result string) string {
  1340. return fmt.Sprintf("The fruit with the longest name is %s.", result)
  1341. },
  1342. )
  1343. fmt.Println(longestName)
  1344. // Output:
  1345. // The fruit with the longest name is passionfruit.
  1346. }
  1347. // The following code example demonstrates how to use AllT
  1348. // to get the students having all marks greater than 70.
  1349. func ExampleQuery_AllT() {
  1350. type Student struct {
  1351. Name string
  1352. Marks []int
  1353. }
  1354. students := []Student{
  1355. {Name: "Hugo", Marks: []int{91, 88, 76, 93}},
  1356. {Name: "Rick", Marks: []int{70, 73, 66, 90}},
  1357. {Name: "Michael", Marks: []int{73, 80, 75, 88}},
  1358. {Name: "Fadi", Marks: []int{82, 75, 66, 84}},
  1359. {Name: "Peter", Marks: []int{67, 78, 70, 82}},
  1360. }
  1361. var approvedStudents []Student
  1362. From(students).
  1363. WhereT(
  1364. func(student Student) bool {
  1365. return From(student.Marks).
  1366. AllT(
  1367. func(mark int) bool { return mark > 70 },
  1368. )
  1369. },
  1370. ).
  1371. ToSlice(&approvedStudents)
  1372. //List of approved students
  1373. for _, student := range approvedStudents {
  1374. fmt.Println(student.Name)
  1375. }
  1376. // Output:
  1377. // Hugo
  1378. // Michael
  1379. }
  1380. // The following code example demonstrates how to use AnyWithT
  1381. // to get the students with any mark lower than 70.
  1382. func ExampleQuery_AnyWithT() {
  1383. type Student struct {
  1384. Name string
  1385. Marks []int
  1386. }
  1387. students := []Student{
  1388. {Name: "Hugo", Marks: []int{91, 88, 76, 93}},
  1389. {Name: "Rick", Marks: []int{70, 73, 66, 90}},
  1390. {Name: "Michael", Marks: []int{73, 80, 75, 88}},
  1391. {Name: "Fadi", Marks: []int{82, 75, 66, 84}},
  1392. {Name: "Peter", Marks: []int{67, 78, 70, 82}},
  1393. }
  1394. var studentsWithAnyMarkLt70 []Student
  1395. From(students).
  1396. WhereT(
  1397. func(student Student) bool {
  1398. return From(student.Marks).
  1399. AnyWithT(
  1400. func(mark int) bool { return mark < 70 },
  1401. )
  1402. },
  1403. ).
  1404. ToSlice(&studentsWithAnyMarkLt70)
  1405. //List of students with any mark lower than 70
  1406. for _, student := range studentsWithAnyMarkLt70 {
  1407. fmt.Println(student.Name)
  1408. }
  1409. // Output:
  1410. // Rick
  1411. // Fadi
  1412. // Peter
  1413. }
  1414. // The following code example demonstrates how to use CountWithT
  1415. // to count the elements in an slice that satisfy a condition.
  1416. func ExampleQuery_CountWithT() {
  1417. type Pet struct {
  1418. Name string
  1419. Vaccinated bool
  1420. }
  1421. pets := []Pet{
  1422. {Name: "Barley", Vaccinated: true},
  1423. {Name: "Boots", Vaccinated: false},
  1424. {Name: "Whiskers", Vaccinated: false},
  1425. }
  1426. numberUnvaccinated := From(pets).
  1427. CountWithT(
  1428. func(p Pet) bool { return p.Vaccinated == false },
  1429. )
  1430. fmt.Printf("There are %d unvaccinated animals.", numberUnvaccinated)
  1431. //Output:
  1432. //There are 2 unvaccinated animals.
  1433. }
  1434. // The following code example demonstrates how to use DistinctByT
  1435. // to return distinct elements from a slice of structs.
  1436. func ExampleQuery_DistinctByT() {
  1437. type Product struct {
  1438. Name string
  1439. Code int
  1440. }
  1441. products := []Product{
  1442. {Name: "apple", Code: 9},
  1443. {Name: "orange", Code: 4},
  1444. {Name: "apple", Code: 9},
  1445. {Name: "lemon", Code: 12},
  1446. }
  1447. //Exclude duplicates.
  1448. var noduplicates []Product
  1449. From(products).
  1450. DistinctByT(
  1451. func(item Product) int { return item.Code },
  1452. ).
  1453. ToSlice(&noduplicates)
  1454. for _, product := range noduplicates {
  1455. fmt.Printf("%s %d\n", product.Name, product.Code)
  1456. }
  1457. // Output:
  1458. // apple 9
  1459. // orange 4
  1460. // lemon 12
  1461. }
  1462. // The following code example demonstrates how to use ExceptByT
  1463. func ExampleQuery_ExceptByT() {
  1464. type Product struct {
  1465. Name string
  1466. Code int
  1467. }
  1468. fruits1 := []Product{
  1469. {Name: "orange", Code: 4},
  1470. {Name: "apple", Code: 9},
  1471. {Name: "lemon", Code: 12},
  1472. {Name: "apple", Code: 9},
  1473. }
  1474. fruits2 := []Product{
  1475. {Name: "apple", Code: 9},
  1476. }
  1477. //Order and exclude duplicates.
  1478. var except []Product
  1479. From(fruits1).
  1480. ExceptByT(From(fruits2),
  1481. func(item Product) int { return item.Code },
  1482. ).
  1483. ToSlice(&except)
  1484. for _, product := range except {
  1485. fmt.Printf("%s %d\n", product.Name, product.Code)
  1486. }
  1487. // Output:
  1488. // orange 4
  1489. // lemon 12
  1490. }
  1491. // The following code example demonstrates how to use FirstWithT
  1492. // to return the first element of an array that satisfies a condition.
  1493. func ExampleQuery_FirstWithT() {
  1494. numbers := []int{9, 34, 65, 92, 87, 435, 3, 54, 83, 23, 87, 435, 67, 12, 19}
  1495. first := From(numbers).
  1496. FirstWithT(
  1497. func(item int) bool { return item > 80 },
  1498. )
  1499. fmt.Println(first)
  1500. // Output:
  1501. // 92
  1502. }
  1503. // The following code example demonstrates how to use ForEach
  1504. // to output all elements of an array.
  1505. func ExampleQuery_ForEach() {
  1506. fruits := []string{"orange", "apple", "lemon", "apple"}
  1507. From(fruits).ForEach(func(fruit interface{}) {
  1508. fmt.Println(fruit)
  1509. })
  1510. // Output:
  1511. // orange
  1512. // apple
  1513. // lemon
  1514. // apple
  1515. }
  1516. // The following code example demonstrates how to use ForEachIndexed
  1517. // to output all elements of an array with its index.
  1518. func ExampleQuery_ForEachIndexed() {
  1519. fruits := []string{"orange", "apple", "lemon", "apple"}
  1520. From(fruits).ForEachIndexed(func(i int, fruit interface{}) {
  1521. fmt.Printf("%d.%s\n", i, fruit)
  1522. })
  1523. // Output:
  1524. // 0.orange
  1525. // 1.apple
  1526. // 2.lemon
  1527. // 3.apple
  1528. }
  1529. // The following code example demonstrates how to use ForEachT
  1530. // to output all elements of an array.
  1531. func ExampleQuery_ForEachT() {
  1532. fruits := []string{"orange", "apple", "lemon", "apple"}
  1533. From(fruits).ForEachT(func(fruit string) {
  1534. fmt.Println(fruit)
  1535. })
  1536. // Output:
  1537. // orange
  1538. // apple
  1539. // lemon
  1540. // apple
  1541. }
  1542. // The following code example demonstrates how to use ForEachIndexedT
  1543. // to output all elements of an array with its index.
  1544. func ExampleQuery_ForEachIndexedT() {
  1545. fruits := []string{"orange", "apple", "lemon", "apple"}
  1546. From(fruits).ForEachIndexedT(func(i int, fruit string) {
  1547. fmt.Printf("%d.%s\n", i, fruit)
  1548. })
  1549. // Output:
  1550. // 0.orange
  1551. // 1.apple
  1552. // 2.lemon
  1553. // 3.apple
  1554. }
  1555. // The following code example demonstrates how to use GroupByT
  1556. // to group the elements of a slice.
  1557. func ExampleQuery_GroupByT() {
  1558. type Pet struct {
  1559. Name string
  1560. Age int
  1561. }
  1562. // Create a list of pets.
  1563. pets := []Pet{
  1564. {Name: "Barley", Age: 8},
  1565. {Name: "Boots", Age: 4},
  1566. {Name: "Whiskers", Age: 1},
  1567. {Name: "Daisy", Age: 4},
  1568. }
  1569. // Group the pets using Age as the key value
  1570. // and selecting only the pet's Name for each value.
  1571. var query []Group
  1572. From(pets).GroupByT(
  1573. func(p Pet) int { return p.Age },
  1574. func(p Pet) string { return p.Name },
  1575. ).OrderByT(
  1576. func(g Group) int { return g.Key.(int) },
  1577. ).ToSlice(&query)
  1578. for _, petGroup := range query {
  1579. fmt.Printf("%d\n", petGroup.Key)
  1580. for _, petName := range petGroup.Group {
  1581. fmt.Printf(" %s\n", petName)
  1582. }
  1583. }
  1584. // Output:
  1585. // 1
  1586. // Whiskers
  1587. // 4
  1588. // Boots
  1589. // Daisy
  1590. // 8
  1591. // Barley
  1592. }
  1593. // The following code example demonstrates how to use GroupJoinT
  1594. // to perform a grouped join on two slices.
  1595. func ExampleQuery_GroupJoinT() {
  1596. type Person struct {
  1597. Name string
  1598. }
  1599. type Pet struct {
  1600. Name string
  1601. Owner Person
  1602. }
  1603. magnus := Person{Name: "Hedlund, Magnus"}
  1604. terry := Person{Name: "Adams, Terry"}
  1605. charlotte := Person{Name: "Weiss, Charlotte"}
  1606. barley := Pet{Name: "Barley", Owner: terry}
  1607. boots := Pet{Name: "Boots", Owner: terry}
  1608. whiskers := Pet{Name: "Whiskers", Owner: charlotte}
  1609. daisy := Pet{Name: "Daisy", Owner: magnus}
  1610. people := []Person{magnus, terry, charlotte}
  1611. pets := []Pet{barley, boots, whiskers, daisy}
  1612. // Create a slice where each element is a KeyValue
  1613. // that contains a person's name as the key and a slice of strings
  1614. // of names of the pets they own as a value.
  1615. q := []KeyValue{}
  1616. From(people).
  1617. GroupJoinT(From(pets),
  1618. func(p Person) Person { return p },
  1619. func(p Pet) Person { return p.Owner },
  1620. func(person Person, pets []Pet) KeyValue {
  1621. var petNames []string
  1622. From(pets).
  1623. SelectT(
  1624. func(pet Pet) string { return pet.Name },
  1625. ).
  1626. ToSlice(&petNames)
  1627. return KeyValue{person.Name, petNames}
  1628. },
  1629. ).ToSlice(&q)
  1630. for _, obj := range q {
  1631. // Output the owner's name.
  1632. fmt.Printf("%s:\n", obj.Key)
  1633. // Output each of the owner's pet's names.
  1634. for _, petName := range obj.Value.([]string) {
  1635. fmt.Printf(" %s\n", petName)
  1636. }
  1637. }
  1638. // Output:
  1639. // Hedlund, Magnus:
  1640. // Daisy
  1641. // Adams, Terry:
  1642. // Barley
  1643. // Boots
  1644. // Weiss, Charlotte:
  1645. // Whiskers
  1646. }
  1647. // The following code example demonstrates how to use IntersectByT
  1648. // to return the elements that appear in each of two slices of products
  1649. // with same Code.
  1650. func ExampleQuery_IntersectByT() {
  1651. type Product struct {
  1652. Name string
  1653. Code int
  1654. }
  1655. store1 := []Product{
  1656. {Name: "orange", Code: 4},
  1657. {Name: "apple", Code: 9},
  1658. }
  1659. store2 := []Product{
  1660. {Name: "lemon", Code: 12},
  1661. {Name: "apple", Code: 9},
  1662. }
  1663. var duplicates []Product
  1664. From(store1).
  1665. IntersectByT(From(store2),
  1666. func(p Product) int { return p.Code },
  1667. ).
  1668. ToSlice(&duplicates)
  1669. for _, p := range duplicates {
  1670. fmt.Println(p.Name, "", p.Code)
  1671. }
  1672. // Output:
  1673. // apple 9
  1674. }
  1675. // The following code example demonstrates how to use JoinT
  1676. // to perform an inner join of two slices based on a common key.
  1677. func ExampleQuery_JoinT() {
  1678. type Person struct {
  1679. Name string
  1680. }
  1681. type Pet struct {
  1682. Name string
  1683. Owner Person
  1684. }
  1685. magnus := Person{Name: "Hedlund, Magnus"}
  1686. terry := Person{Name: "Adams, Terry"}
  1687. charlotte := Person{Name: "Weiss, Charlotte"}
  1688. barley := Pet{Name: "Barley", Owner: terry}
  1689. boots := Pet{Name: "Boots", Owner: terry}
  1690. whiskers := Pet{Name: "Whiskers", Owner: charlotte}
  1691. daisy := Pet{Name: "Daisy", Owner: magnus}
  1692. people := []Person{magnus, terry, charlotte}
  1693. pets := []Pet{barley, boots, whiskers, daisy}
  1694. // Create a list of Person-Pet pairs where
  1695. // each element is an anonymous type that contains a
  1696. // Pet's name and the name of the Person that owns the Pet.
  1697. query := []string{}
  1698. From(people).
  1699. JoinT(From(pets),
  1700. func(person Person) Person { return person },
  1701. func(pet Pet) Person { return pet.Owner },
  1702. func(person Person, pet Pet) string { return fmt.Sprintf("%s - %s", person.Name, pet.Name) },
  1703. ).ToSlice(&query)
  1704. for _, line := range query {
  1705. fmt.Println(line)
  1706. }
  1707. //Output:
  1708. //Hedlund, Magnus - Daisy
  1709. //Adams, Terry - Barley
  1710. //Adams, Terry - Boots
  1711. //Weiss, Charlotte - Whiskers
  1712. }
  1713. // The following code example demonstrates how to use LastWithT
  1714. // to return the last element of an array.
  1715. func ExampleQuery_LastWithT() {
  1716. numbers := []int{9, 34, 65, 92, 87, 435, 3, 54,
  1717. 83, 23, 87, 67, 12, 19}
  1718. last := From(numbers).
  1719. LastWithT(
  1720. func(n int) bool { return n > 80 },
  1721. )
  1722. fmt.Println(last)
  1723. //Output:
  1724. //87
  1725. }
  1726. // The following code example demonstrates how to use OrderByDescendingT
  1727. // to order an slice.
  1728. func ExampleQuery_OrderByDescendingT() {
  1729. type Player struct {
  1730. Name string
  1731. Points int64
  1732. }
  1733. players := []Player{
  1734. {Name: "Hugo", Points: 4757},
  1735. {Name: "Rick", Points: 7365},
  1736. {Name: "Michael", Points: 2857},
  1737. {Name: "Fadi", Points: 85897},
  1738. {Name: "Peter", Points: 48576},
  1739. }
  1740. //Order and get the top 3 players
  1741. var top3Players []KeyValue
  1742. From(players).
  1743. OrderByDescendingT(
  1744. func(p Player) int64 { return p.Points },
  1745. ).
  1746. Take(3).
  1747. SelectIndexedT(
  1748. func(i int, p Player) KeyValue { return KeyValue{Key: i + 1, Value: p} },
  1749. ).
  1750. ToSlice(&top3Players)
  1751. for _, rank := range top3Players {
  1752. fmt.Printf(
  1753. "Rank: #%d - Player: %s - Points: %d\n",
  1754. rank.Key,
  1755. rank.Value.(Player).Name,
  1756. rank.Value.(Player).Points,
  1757. )
  1758. }
  1759. // Output:
  1760. // Rank: #1 - Player: Fadi - Points: 85897
  1761. // Rank: #2 - Player: Peter - Points: 48576
  1762. // Rank: #3 - Player: Rick - Points: 7365
  1763. }
  1764. // The following code example demonstrates how to use OrderByT
  1765. // to sort the elements of a slice.
  1766. func ExampleQuery_OrderByT() {
  1767. type Pet struct {
  1768. Name string
  1769. Age int
  1770. }
  1771. // Create a list of pets.
  1772. pets := []Pet{
  1773. {Name: "Barley", Age: 8},
  1774. {Name: "Boots", Age: 4},
  1775. {Name: "Whiskers", Age: 1},
  1776. {Name: "Daisy", Age: 4},
  1777. }
  1778. var orderedPets []Pet
  1779. From(pets).
  1780. OrderByT(
  1781. func(pet Pet) int { return pet.Age },
  1782. ).
  1783. ToSlice(&orderedPets)
  1784. for _, pet := range orderedPets {
  1785. fmt.Println(pet.Name, "-", pet.Age)
  1786. }
  1787. // Output:
  1788. // Whiskers - 1
  1789. // Boots - 4
  1790. // Daisy - 4
  1791. // Barley - 8
  1792. }
  1793. // The following code example demonstrates how to use SelectT
  1794. // to project over a slice.
  1795. func ExampleQuery_SelectT() {
  1796. squares := []int{}
  1797. Range(1, 10).
  1798. SelectT(
  1799. func(x int) int { return x * x },
  1800. ).
  1801. ToSlice(&squares)
  1802. fmt.Println(squares)
  1803. // Output:
  1804. // [1 4 9 16 25 36 49 64 81 100]
  1805. }
  1806. // The following code example demonstrates how to use SelectIndexedT
  1807. // to determine if the value in a slice of int match their position
  1808. // in the slice.
  1809. func ExampleQuery_SelectIndexedT() {
  1810. numbers := []int{5, 4, 1, 3, 9, 8, 6, 7, 2, 0}
  1811. var numsInPlace []KeyValue
  1812. From(numbers).
  1813. SelectIndexedT(
  1814. func(index, num int) KeyValue { return KeyValue{Key: num, Value: (num == index)} },
  1815. ).
  1816. ToSlice(&numsInPlace)
  1817. fmt.Println("Number: In-place?")
  1818. for _, n := range numsInPlace {
  1819. fmt.Printf("%d: %t\n", n.Key, n.Value)
  1820. }
  1821. // Output:
  1822. // Number: In-place?
  1823. // 5: false
  1824. // 4: false
  1825. // 1: false
  1826. // 3: true
  1827. // 9: false
  1828. // 8: false
  1829. // 6: true
  1830. // 7: true
  1831. // 2: false
  1832. // 0: false
  1833. }
  1834. // The following code example demonstrates how to use SelectManyT
  1835. // to perform a one-to-many projection over a slice
  1836. func ExampleQuery_SelectManyByT() {
  1837. type Pet struct {
  1838. Name string
  1839. }
  1840. type Person struct {
  1841. Name string
  1842. Pets []Pet
  1843. }
  1844. magnus := Person{
  1845. Name: "Hedlund, Magnus",
  1846. Pets: []Pet{{Name: "Daisy"}},
  1847. }
  1848. terry := Person{
  1849. Name: "Adams, Terry",
  1850. Pets: []Pet{{Name: "Barley"}, {Name: "Boots"}},
  1851. }
  1852. charlotte := Person{
  1853. Name: "Weiss, Charlotte",
  1854. Pets: []Pet{{Name: "Whiskers"}},
  1855. }
  1856. people := []Person{magnus, terry, charlotte}
  1857. var results []string
  1858. From(people).
  1859. SelectManyByT(
  1860. func(person Person) Query { return From(person.Pets) },
  1861. func(pet Pet, person Person) interface{} {
  1862. return fmt.Sprintf("Owner: %s, Pet: %s", person.Name, pet.Name)
  1863. },
  1864. ).
  1865. ToSlice(&results)
  1866. for _, result := range results {
  1867. fmt.Println(result)
  1868. }
  1869. // Output:
  1870. // Owner: Hedlund, Magnus, Pet: Daisy
  1871. // Owner: Adams, Terry, Pet: Barley
  1872. // Owner: Adams, Terry, Pet: Boots
  1873. // Owner: Weiss, Charlotte, Pet: Whiskers
  1874. }
  1875. // The following code example demonstrates how to use SelectManyT
  1876. // to perform a projection over a list of sentences and rank the
  1877. // top 5 most used words
  1878. func ExampleQuery_SelectManyT() {
  1879. sentences := []string{
  1880. "the quick brown fox jumps over the lazy dog",
  1881. "pack my box with five dozen liquor jugs",
  1882. "several fabulous dixieland jazz groups played with quick tempo",
  1883. "back in my quaint garden jaunty zinnias vie with flaunting phlox",
  1884. "five or six big jet planes zoomed quickly by the new tower",
  1885. "I quickly explained that many big jobs involve few hazards",
  1886. "The wizard quickly jinxed the gnomes before they vaporized",
  1887. }
  1888. var results []string
  1889. From(sentences).
  1890. //Split the sentences in words
  1891. SelectManyT(func(sentence string) Query {
  1892. return From(strings.Split(sentence, " "))
  1893. }).
  1894. //Grouping by word
  1895. GroupByT(
  1896. func(word string) string { return word },
  1897. func(word string) string { return word },
  1898. ).
  1899. //Ordering by word counts
  1900. OrderByDescendingT(func(wordGroup Group) int {
  1901. return len(wordGroup.Group)
  1902. }).
  1903. //Then order by word
  1904. ThenByT(func(wordGroup Group) string {
  1905. return wordGroup.Key.(string)
  1906. }).
  1907. //Take the top 5
  1908. Take(5).
  1909. //Project the words using the index as rank
  1910. SelectIndexedT(func(index int, wordGroup Group) string {
  1911. return fmt.Sprintf("Rank: #%d, Word: %s, Counts: %d", index+1, wordGroup.Key, len(wordGroup.Group))
  1912. }).
  1913. ToSlice(&results)
  1914. for _, result := range results {
  1915. fmt.Println(result)
  1916. }
  1917. // Output:
  1918. // Rank: #1, Word: the, Counts: 4
  1919. // Rank: #2, Word: quickly, Counts: 3
  1920. // Rank: #3, Word: with, Counts: 3
  1921. // Rank: #4, Word: big, Counts: 2
  1922. // Rank: #5, Word: five, Counts: 2
  1923. }
  1924. // The following code example demonstrates how to use SelectManyIndexedT
  1925. // to perform a one-to-many projection over an slice of log files and
  1926. // print out their contents.
  1927. func ExampleQuery_SelectManyIndexedT() {
  1928. type LogFile struct {
  1929. Name string
  1930. Lines []string
  1931. }
  1932. file1 := LogFile{
  1933. Name: "file1.log",
  1934. Lines: []string{
  1935. "INFO: 2013/11/05 18:11:01 main.go:44: Special Information",
  1936. "WARNING: 2013/11/05 18:11:01 main.go:45: There is something you need to know about",
  1937. "ERROR: 2013/11/05 18:11:01 main.go:46: Something has failed",
  1938. },
  1939. }
  1940. file2 := LogFile{
  1941. Name: "file2.log",
  1942. Lines: []string{
  1943. "INFO: 2013/11/05 18:11:01 main.go:46: Everything is ok",
  1944. },
  1945. }
  1946. file3 := LogFile{
  1947. Name: "file3.log",
  1948. Lines: []string{
  1949. "2013/11/05 18:42:26 Hello World",
  1950. },
  1951. }
  1952. logFiles := []LogFile{file1, file2, file3}
  1953. var results []string
  1954. From(logFiles).
  1955. SelectManyIndexedT(func(fileIndex int, file LogFile) Query {
  1956. return From(file.Lines).
  1957. SelectIndexedT(func(lineIndex int, line string) string {
  1958. return fmt.Sprintf("File:[%d] - %s => line: %d - %s", fileIndex+1, file.Name, lineIndex+1, line)
  1959. })
  1960. }).
  1961. ToSlice(&results)
  1962. for _, result := range results {
  1963. fmt.Println(result)
  1964. }
  1965. // Output:
  1966. // File:[1] - file1.log => line: 1 - INFO: 2013/11/05 18:11:01 main.go:44: Special Information
  1967. // File:[1] - file1.log => line: 2 - WARNING: 2013/11/05 18:11:01 main.go:45: There is something you need to know about
  1968. // File:[1] - file1.log => line: 3 - ERROR: 2013/11/05 18:11:01 main.go:46: Something has failed
  1969. // File:[2] - file2.log => line: 1 - INFO: 2013/11/05 18:11:01 main.go:46: Everything is ok
  1970. // File:[3] - file3.log => line: 1 - 2013/11/05 18:42:26 Hello World
  1971. }
  1972. // The following code example demonstrates how to use SelectManyByIndexedT
  1973. // to perform a one-to-many projection over an array and use the index of
  1974. // each outer element.
  1975. func ExampleQuery_SelectManyByIndexedT() {
  1976. type Pet struct {
  1977. Name string
  1978. }
  1979. type Person struct {
  1980. Name string
  1981. Pets []Pet
  1982. }
  1983. magnus := Person{
  1984. Name: "Hedlund, Magnus",
  1985. Pets: []Pet{{Name: "Daisy"}},
  1986. }
  1987. terry := Person{
  1988. Name: "Adams, Terry",
  1989. Pets: []Pet{{Name: "Barley"}, {Name: "Boots"}},
  1990. }
  1991. charlotte := Person{
  1992. Name: "Weiss, Charlotte",
  1993. Pets: []Pet{{Name: "Whiskers"}},
  1994. }
  1995. people := []Person{magnus, terry, charlotte}
  1996. var results []string
  1997. From(people).
  1998. SelectManyByIndexedT(
  1999. func(index int, person Person) Query {
  2000. return From(person.Pets).
  2001. SelectT(func(pet Pet) string {
  2002. return fmt.Sprintf("%d - %s", index, pet.Name)
  2003. })
  2004. },
  2005. func(indexedPet string, person Person) string {
  2006. return fmt.Sprintf("Pet: %s, Owner: %s", indexedPet, person.Name)
  2007. },
  2008. ).
  2009. ToSlice(&results)
  2010. for _, result := range results {
  2011. fmt.Println(result)
  2012. }
  2013. // Output:
  2014. // Pet: 0 - Daisy, Owner: Hedlund, Magnus
  2015. // Pet: 1 - Barley, Owner: Adams, Terry
  2016. // Pet: 1 - Boots, Owner: Adams, Terry
  2017. // Pet: 2 - Whiskers, Owner: Weiss, Charlotte
  2018. }
  2019. //The following code example demonstrates how to use SingleWithT
  2020. // to select the only element of a slice that satisfies a condition.
  2021. func ExampleQuery_SingleWithT() {
  2022. fruits := []string{"apple", "banana", "mango", "orange", "passionfruit", "grape"}
  2023. fruit := From(fruits).
  2024. SingleWithT(
  2025. func(f string) bool { return len(f) > 10 },
  2026. )
  2027. fmt.Println(fruit)
  2028. // Output:
  2029. // passionfruit
  2030. }
  2031. // The following code example demonstrates how to use SkipWhileT
  2032. // to skip elements of an array as long as a condition is true.
  2033. func ExampleQuery_SkipWhileT() {
  2034. grades := []int{59, 82, 70, 56, 92, 98, 85}
  2035. var lowerGrades []int
  2036. From(grades).
  2037. OrderByDescendingT(
  2038. func(g int) int { return g },
  2039. ).
  2040. SkipWhileT(
  2041. func(g int) bool { return g >= 80 },
  2042. ).
  2043. ToSlice(&lowerGrades)
  2044. //"All grades below 80:
  2045. fmt.Println(lowerGrades)
  2046. // Output:
  2047. // [70 59 56]
  2048. }
  2049. // The following code example demonstrates how to use SkipWhileIndexedT
  2050. // to skip elements of an array as long as a condition that depends
  2051. // on the element's index is true.
  2052. func ExampleQuery_SkipWhileIndexedT() {
  2053. amounts := []int{5000, 2500, 9000, 8000, 6500, 4000, 1500, 5500}
  2054. var query []int
  2055. From(amounts).
  2056. SkipWhileIndexedT(
  2057. func(index int, amount int) bool { return amount > index*1000 },
  2058. ).
  2059. ToSlice(&query)
  2060. fmt.Println(query)
  2061. // Output:
  2062. // [4000 1500 5500]
  2063. }
  2064. // The following code example demonstrates how to use SortT
  2065. // to order elements of an slice.
  2066. func ExampleQuery_SortT() {
  2067. type Pet struct {
  2068. Name string
  2069. Age int
  2070. }
  2071. // Create a list of pets.
  2072. pets := []Pet{
  2073. {Name: "Barley", Age: 8},
  2074. {Name: "Boots", Age: 4},
  2075. {Name: "Whiskers", Age: 1},
  2076. {Name: "Daisy", Age: 4},
  2077. }
  2078. orderedPets := []Pet{}
  2079. From(pets).
  2080. SortT(
  2081. func(pet1 Pet, pet2 Pet) bool { return pet1.Age < pet2.Age },
  2082. ).
  2083. ToSlice(&orderedPets)
  2084. for _, pet := range orderedPets {
  2085. fmt.Println(pet.Name, "-", pet.Age)
  2086. }
  2087. // Output:
  2088. // Whiskers - 1
  2089. // Boots - 4
  2090. // Daisy - 4
  2091. // Barley - 8
  2092. }
  2093. // The following code example demonstrates how to use TakeWhileT
  2094. // to return elements from the start of a slice.
  2095. func ExampleQuery_TakeWhileT() {
  2096. fruits := []string{"apple", "banana", "mango", "orange", "passionfruit", "grape"}
  2097. var query []string
  2098. From(fruits).
  2099. TakeWhileT(
  2100. func(fruit string) bool { return fruit != "orange" },
  2101. ).
  2102. ToSlice(&query)
  2103. fmt.Println(query)
  2104. // Output:
  2105. // [apple banana mango]
  2106. }
  2107. // The following code example demonstrates how to use TakeWhileIndexedT
  2108. // to return elements from the start of a slice as long asa condition
  2109. // that uses the element's index is true.
  2110. func ExampleQuery_TakeWhileIndexedT() {
  2111. fruits := []string{"apple", "passionfruit", "banana", "mango",
  2112. "orange", "blueberry", "grape", "strawberry"}
  2113. var query []string
  2114. From(fruits).
  2115. TakeWhileIndexedT(
  2116. func(index int, fruit string) bool { return len(fruit) >= index },
  2117. ).
  2118. ToSlice(&query)
  2119. fmt.Println(query)
  2120. // Output:
  2121. // [apple passionfruit banana mango orange blueberry]
  2122. }
  2123. // The following code example demonstrates how to use ToMapBy
  2124. // by using a key and value selectors to populate a map.
  2125. func ExampleQuery_ToMapByT() {
  2126. type Product struct {
  2127. Name string
  2128. Code int
  2129. }
  2130. products := []Product{
  2131. {Name: "orange", Code: 4},
  2132. {Name: "apple", Code: 9},
  2133. {Name: "lemon", Code: 12},
  2134. {Name: "apple", Code: 9},
  2135. }
  2136. map1 := map[int]string{}
  2137. From(products).
  2138. ToMapByT(&map1,
  2139. func(item Product) int { return item.Code },
  2140. func(item Product) string { return item.Name },
  2141. )
  2142. fmt.Println(map1[4])
  2143. fmt.Println(map1[9])
  2144. fmt.Println(map1[12])
  2145. // Output:
  2146. // orange
  2147. // apple
  2148. // lemon
  2149. }
  2150. // The following code example demonstrates how to use WhereT
  2151. // to filter a slices.
  2152. func ExampleQuery_WhereT() {
  2153. fruits := []string{"apple", "passionfruit", "banana", "mango",
  2154. "orange", "blueberry", "grape", "strawberry"}
  2155. var query []string
  2156. From(fruits).
  2157. WhereT(
  2158. func(f string) bool { return len(f) > 6 },
  2159. ).
  2160. ToSlice(&query)
  2161. fmt.Println(query)
  2162. // Output:
  2163. // [passionfruit blueberry strawberry]
  2164. }
  2165. // The following code example demonstrates how to use WhereIndexedT
  2166. // to filter a slice based on a predicate that involves the index of each element.
  2167. func ExampleQuery_WhereIndexedT() {
  2168. numbers := []int{0, 30, 20, 15, 90, 85, 40, 75}
  2169. var query []int
  2170. From(numbers).
  2171. WhereIndexedT(
  2172. func(index int, number int) bool { return number <= index*10 },
  2173. ).
  2174. ToSlice(&query)
  2175. fmt.Println(query)
  2176. // Output:
  2177. // [0 20 15 40]
  2178. }
  2179. // The following code example demonstrates how to use the ZipT
  2180. // method to merge two slices.
  2181. func ExampleQuery_ZipT() {
  2182. number := []int{1, 2, 3, 4, 5}
  2183. words := []string{"one", "two", "three"}
  2184. q := From(number).
  2185. ZipT(From(words),
  2186. func(a int, b string) []interface{} { return []interface{}{a, b} },
  2187. )
  2188. fmt.Println(q.Results())
  2189. // Output:
  2190. // [[1 one] [2 two] [3 three]]
  2191. }
  2192. // The following code example demonstrates how to use the FromChannelT
  2193. // to make a Query from typed channel.
  2194. func ExampleFromChannelT() {
  2195. ch := make(chan string, 3)
  2196. ch <- "one"
  2197. ch <- "two"
  2198. ch <- "three"
  2199. close(ch)
  2200. q := FromChannelT(ch)
  2201. fmt.Println(q.Results())
  2202. // Output:
  2203. // [one two three]
  2204. }