Skip to content

Latest commit

 

History

History
300 lines (225 loc) · 10.3 KB

README.md

File metadata and controls

300 lines (225 loc) · 10.3 KB

LINQ for Go with type parameters

LINQ (Language-Integrated Query) is a component that adds data querying capabilities of Microsoft .Net languages. This package provides the implementation of the LINQ functions for Go with type parameters.

Quick Start

Install

go get github.com/makiuchi-d/linq/v2

Example

package main

import (
	"fmt"

	"github.com/makiuchi-d/linq/v2"
)

type Student struct {
	Name  string
	Class string
	Score int
}

func main() {
	students := []Student{
		// generated by https://testdata.userlocal.jp/
		{"熊木 緑", "1-A", 953},
		{"山本 千佳子", "1-C", 559},
		{"星 雅彦", "1-B", 136},
		{"齊藤 綾子", "1-A", 149},
		{"杉原 和己", "1-C", 737},
		{"山路 信之", "1-B", 425},
		{"佐々木 淑子", "1-C", 759},
		{"三宅 直人", "1-B", 594},
		{"緒方 俊", "1-B", 405},
		{"稲井 隆生", "1-A", 495},
	}

	e1 := linq.FromSlice(students)
	e2 := linq.Where(e1, func(s Student) (bool, error) { return s.Class == "1-B", nil })
	e3 := linq.OrderByDescending(e2, func(s Student) (int, error) { return s.Score, nil })

	// go1.23.0 or later
	for s, err := range e3.All() {
		if err != nil {
			panic(err)
		}
		fmt.Printf("%d %s\n", s.Score, s.Name)
	}

	fmt.Println("----")

	// it also works in older go
	err := linq.ForEach(e3, func(s Student) error {
		fmt.Printf("%d %s\n", s.Score, s.Name)
		return nil
	})
	if err != nil {
		panic(err)
	}
}

Output:

594 三宅 直人
425 山路 信之
405 緒方 俊
136 星 雅彦
----
594 三宅 直人
425 山路 信之
405 緒方 俊
136 星 雅彦

Functions

italics are unique to this package.

Sorting Data

  • OrderBy
  • OrderByDescending
  • OrderByFunc
  • ThenBy
  • ThenByDescending
  • Reverse

Set Operations

  • Distinct
  • DistinctBy
  • Except
  • ExceptBy
  • Intersect
  • IntersectBy
  • Union
  • UnionBy

Filtering Data

  • Where

Quantifier Operations

  • All
  • Any
  • Contains
  • ContainsFunc

Projection Operations

  • Select
  • SelectMany
  • Zip

Partitioning Data

  • Skip
  • SkipLast
  • SkipWhile
  • Take
  • TakeLast
  • TakeWhile
  • Chunk

Join Operations

  • GroupJoin
  • Join

Grouping Data

  • GroupBy

Generation Operations

  • DefaultIfEmpty
  • Empty
  • Range
  • Repeat

Element Operations

  • ElementAt
  • ElementAtOrDefault
  • First
  • FirstOrDefault
  • Last
  • LastOrDefault
  • Single
  • SingleOrDefault

Converting Data Types

  • FromMap
  • FromSlice
  • ToMap
  • ToMapFunc
  • ToSlice

Concatenation Operations

  • Concat

Aggregation Operations

  • Aggregate
  • Average
  • Count
  • Max
  • MaxBy
  • MaxByFunc
  • Min
  • MinBy
  • MinByFunc
  • Sum
  • Sumf

Other

  • ForEach
  • Generator

C# LINQ Documents