linq_rs 0.2.0

A LINQ-like query library for Rust iterators — no external dependencies
Documentation
  • Coverage
  • 100%
    126 out of 126 items documented35 out of 118 items with examples
  • Size
  • Source code size: 340.0 kB This is the summed size of all the files inside the crates.io package for this release.
  • Documentation size: 12.5 MB This is the summed size of all files generated by rustdoc for all configured targets
  • Ø build duration
  • this release: 2s Average build duration of successful builds.
  • all releases: 10s Average build duration of successful builds in releases after 2024-10-23.
  • Links
  • TRget88/LinqLikeForRust
    0 0 0
  • crates.io
  • Dependencies
  • Versions
  • Owners
  • TRget88

linq_rs

A LINQ-style query library for Rust — zero external dependencies.

LINQ-shaped query operators over any Iterator, as composable extension methods.

Where familiarity to C# and idiomatic Rust conflict, this crate picks idiomatic Rust (D-005).

System.Linq.Enumerable in .NET 10.0 exposes 74 operator names across 228 overloads, 38 of which take an IEqualityComparer or IComparer.

This crate implements 45 of those 74 names and none of the 38 comparer overloads — the latter deliberately (D-202): Rust expresses that with traits and newtypes, and the honest substitute is the *_by key-selector family.

Not implemented (29): Aggregate, Append, AsEnumerable, Cast, Chunk, Concat, DefaultIfEmpty, ElementAt, ElementAtOrDefault, Index, InfiniteSequence, LeftJoin, LongCount, OfType, Prepend, Reverse, RightJoin, Sequence, SequenceEqual, Shuffle, SkipLast, SkipWhile, TakeLast, TakeWhile, ToArray, ToHashSet, ToList, TryGetNonEnumeratedCount, Zip.

Of the 74, 5 are static generator methods on Enumerable rather than extension methods, so they are free functions here, not LinqExt methods: Empty, InfiniteSequence, Range, Repeat, Sequence.

These numbers are generated by .github/scripts/gen-docs.py from .github/data/, and CI fails if they drift. Do not edit them by hand.

Scope and API rulings live in DECISIONS.md; current-state evidence lives in AUDIT.md.


Quick Start

use linq_rs::LinqExt;

let result: Vec<_> = vec![1, 2, 3, 4, 5, 6]
    .into_iter()
    .where_(|x| x % 2 == 0)   // filter
    .select(|x| x * x)         // project
    .collect();

assert_eq!(result, [4, 16, 36]);

Add to Cargo.toml:

[dependencies]
linq_rs = "0.2"

Do not use 0.1.0. It shipped a then_by that discarded the primary sort key and a skip that turned every unqualified .skip(n) in an importing module into a compile error. Both are fixed in 0.2.0. 0.1.0 is being yanked from crates.io per D-009; update this note to "yanked" once that has run, not before.

See CHANGELOG.md for the full 0.2.0 entry. It is a large one: 0.2.0 cuts the operator surface by a third, renames two methods, and lowers the MSRV to 1.65.


API Reference

Filtering

Rust (linq_rs) C# LINQ equivalent
where_(predicate) Where(predicate)

Projection

Rust C#
select(f) Select(f)
select_many(f) SelectMany(f)

Paging / Slicing

Rust C#
skip_(n) Skip(n)
take_(n) Take(n)

Set Operations

Rust C#
distinct() Distinct()
distinct_by(key_fn) DistinctBy(key_fn)
except(other) Except(other)
except_by(other_keys, key_fn) ExceptBy(other_keys, key_fn)
intersect(other) Intersect(other)
intersect_by(other_keys, key_fn) IntersectBy(other_keys, key_fn)
union_(other) Union(other)
union_by(other, key_fn) UnionBy(other, key_fn)

For except_by / intersect_by, the second argument is the iterable of keys (matching C#). For union_by it is the iterable of items.

| distinct_partial_eq, distinct_by_partial_eq, except_partial_eq, intersect_partial_eq, union_partial_eq | PartialEq escape hatches — same semantics, O(n²), for types that cannot implement Hash. See Performance. |

Ordering

Rust C#
order() Order() (.NET 7+)
order_descending() OrderDescending() (.NET 7+)
order_by(key_fn) OrderBy(key_fn)
order_by_descending(key_fn) OrderByDescending(key_fn)
.then_by(key_fn) .ThenBy(key_fn)
order_by_with(cmp) OrderBy(key_fn, comparer) — for PartialOrd-only keys such as f64
.then_by_with(cmp) .ThenBy(key_fn, comparer)
.then_by_descending(key_fn) .ThenByDescending(key_fn)

The sort is deferred to the first into_iter(): order_by and then_by accumulate comparators, so a chain composes into one lexicographic sort rather than re-sorting at each step. The source is not deferred — order_by collects the receiver when it is called (measured; see Evaluation timing). then_by alone genuinely does nothing but push a comparator.

Aggregation

Rust C#
sum_() Sum()
sum_by(selector) Sum(selector)
count_where(p) Count(p)
min_() Min()
max_() Max()
min_by_key_(key_fn) MinBy(keySelector)
min_by_(cmp) Min(comparer) — comparator form, for PartialOrd-only keys
max_by_(cmp) Max(comparer) — comparator form; ties keep the last maximum
max_by_key_(key_fn) MaxBy(keySelector)
average(selector) Average(selector)

Element Operations

Strict (panicking) variants on the left; _or_default variants return Option<T>.

Rust C#
first() First()
first_or_default() FirstOrDefault()
first_or(default) FirstOrDefault(defaultValue)
first_where(p) FirstOrDefault(p)
last_() Last()
last_or_default() LastOrDefault()
last_or(default) LastOrDefault(defaultValue)
last_where(p) LastOrDefault(p)
single() Single()
try_single() Single(), but returns Result<T, SingleError> instead of throwing
single_or_default() not SingleOrDefault — returns Result<Option<T>, SingleError> so empty and too-many are distinguishable
single_or(default) SingleOrDefault(defaultValue)

Quantifiers

Rust C#
any_(p) Any(p)
all_(p) All(p)
contains_(value) Contains(val)

Joining

Rust C#
inner_join(inner, outerKey, innerKey, resultSel) Join(inner, ok, ik, rs)
group_join(inner, outerKey, innerKey, rs) GroupJoin(inner, ok, ik, rs)

| inner_join_partial_eq, group_join_partial_eq | PartialEq escape hatches — same semantics, O(n²), for types that cannot implement Hash. See Performance. |

Grouping

Rust C#
group_by_key(key_fn) GroupBy(keySelector)
group_by_with_element(key_fn, element_fn) GroupBy(keySelector, elementSelector)
group_by_with_result(key_fn, result_fn) GroupBy(keySelector, resultSelector)
count_by(key_fn) CountBy(keySelector) (.NET 9+)
aggregate_by(key_fn, seed_fn, accum) AggregateBy(keySelector, seedFn, func) (.NET 9+)

group_by_key returns an iterator of Grouping<K, T> — each item has a .key() and .elements(). The overloads transform the elements or fold each group into a single value.

| group_by_key_partial_eq, count_by_partial_eq, aggregate_by_partial_eq | PartialEq escape hatches — same semantics, O(n²), for types that cannot implement Hash. See Performance. |

Conversion

Rust C#
into_hashmap(key_fn) ToDictionary(key_fn)
into_lookup(key_fn) ToLookup(key_fn)

Utility

Rust C#

Source Generators (free functions, not on LinqExt)

Rust C#
linq_rs::range(start, count) Enumerable.Range(start, count)
linq_rs::repeat(val, count) Enumerable.Repeat(val, count)
linq_rs::empty::<T>() Enumerable.Empty<T>()

Realistic Example

use linq_rs::LinqExt;

#[derive(Clone)]
struct Employee { name: &'static str, dept: &'static str, salary: u32 }

let employees = vec![
    Employee { name: "Alice",  dept: "Eng",   salary: 120_000 },
    Employee { name: "Bob",    dept: "Eng",   salary: 95_000  },
    Employee { name: "Carol",  dept: "Sales", salary: 80_000  },
    Employee { name: "Eve",    dept: "Eng",   salary: 130_000 },
];

// High-earners per dept, sorted by dept then salary descending
let result: Vec<_> = employees
    .into_iter()
    .where_(|e| e.salary > 90_000)
    .order_by(|e| e.dept)
    .then_by_descending(|e| e.salary)
        .select(|e| (e.dept, e.name, e.salary))
    .collect();

assert_eq!(result, [
    ("Eng", "Eve",   130_000),
    ("Eng", "Alice", 120_000),
    ("Eng", "Bob",    95_000),
]);

Group Join (Left Outer Join)

use linq_rs::LinqExt;

let depts  = vec![(1u32, "Eng"), (2, "Sales")];
let emps   = vec![(1u32, "Alice"), (1, "Bob"), (2, "Carol")];

let result: Vec<_> = depts.into_iter().group_join(
    emps,
    |(id, _)| *id,
    |(dept_id, _)| *dept_id,
    |(_, dept), members| {
        let names: Vec<_> = members.into_iter().map(|(_, n)| n).collect();
        format!("{dept}: {}", names.join(", "))
    },
).collect();

assert_eq!(result, ["Eng: Alice, Bob", "Sales: Carol"]);

Lookup

use linq_rs::LinqExt;

let data = vec![("fruit", "apple"), ("veggie", "carrot"), ("fruit", "banana")];
let lookup = data.into_iter().into_lookup(|(cat, _)| *cat);

assert_eq!(lookup.get(&"fruit"), &[("fruit", "apple"), ("fruit", "banana")]);

Querying a database

This crate does not touch a database. It has no driver, no connection, and no dependencies; it runs over in-memory iterators.

Its sibling linq_rs_sql builds SQL — compile-time-checked columns, bound parameters, no interpolation — and hands you a string plus its parameters for whatever driver you already use. The two vocabularies are deliberately separate: this crate says where_, that one says filter, and no value passes between them today.

Joining them is the stated next step: one query value with two interpreters, so the same expression can run over a Vec in a unit test and render to SQL in production. No Rust library offers that today. It is tracked as D-002 in DECISIONS.md, and the operator surface here was cut to fit it (D-019) — an operator earns its place only if it could become a SQL clause.

Overlap with std::iter

27 of this crate's 62 LinqExt methods (44%) are a rename or a short composition of something std::iter::Iterator already gives you. If you are not porting C# code, reach for std first.

linq_rs use this instead
all_ all
any_ any
contains_ any()
count_where filter().count()
first next
first_or next
first_or_default next
first_where find
into_hashmap map().collect()
last_ last
last_or last
last_or_default last
last_where filter().last()
max_ max
max_by_ max_by
max_by_key_ max_by_key
min_ min
min_by_ min_by
min_by_key_ min_by_key
order_by_with sort_by
select map
select_many flat_map
skip_ skip
sum_ sum
sum_by map().sum()
take_ take
where_ filter

The remaining 35 have no direct std equivalent — that is the part of this crate with a reason to exist.

Performance — the default is hash-backed

Ten operators need to compare elements or keys. All of them use a hash index by default, and require Eq + Hash:

distinct · distinct_by · except · intersect · union_ · group_by_key · count_by · aggregate_by · inner_join · group_join — plus into_lookup, whose Lookup is hash-indexed throughout.

Each also has a *_partial_eq counterpart that compares with PartialEq and scans linearly:

Default (Eq + Hash, O(n) or O(n + m)) Escape hatch (PartialEq, O(n²))
distinct distinct_partial_eq
distinct_by distinct_by_partial_eq
except except_partial_eq
intersect intersect_partial_eq
union_ union_partial_eq
group_by_key group_by_key_partial_eq
count_by count_by_partial_eq
aggregate_by aggregate_by_partial_eq
inner_join inner_join_partial_eq
group_join group_join_partial_eq

Reach for *_partial_eq only when your type cannot implement Hash — in practice that means floats. vec![1.0, 2.0, 1.0].distinct() does not compile; .distinct_partial_eq() does. The names are long on purpose: this is the slow path and you should have to ask for it.

Be aware of what PartialEq costs you besides time. It does not guarantee reflexivity, so f64::NAN != f64::NAN and every NaN is its own group — a Lookup built that way could not find a NaN key it had just inserted. That is why the default requires Eq, which is Rust's marker for exactly the property these algorithms need. See DECISIONS.md D-101.

Ordering

group_by_key and Lookup yield groups in first-appearance order, which costs an auxiliary index and a Clone bound on the key. count_by and aggregate_by yield in hash order, which is unspecified — sort the result if you need determinism.

Differences from C# LINQ

This crate does not claim per-method equivalence with System.Linq.Enumerable. Most operators here delegate to std::iter, and where std and C# disagree, std wins (D-005). The table above maps names; this section is the normative list of places where the same name does not mean the same behaviour. Every entry is either demonstrated by the runnable example beneath it or sourced to the .NET API reference.

Empty sequences return None; C# throws

Min, Max, MinBy, MaxBy and Average all throw InvalidOperationException on an empty sequence when the element type is a non-nullable value type (Min, MaxBy, Average). The Rust counterparts return None, because that is what Iterator::min, Iterator::max_by_key and Iterator::reduce return.

use linq_rs::LinqExt;

let empty: Vec<i32> = Vec::new();
assert_eq!(empty.clone().into_iter().min_(), None);
assert_eq!(empty.clone().into_iter().max_by_key_(|x| *x), None);
assert_eq!(empty.clone().into_iter().average(|x| x as f64), None);

// Sum is the exception: C# and Rust agree that an empty sum is zero.
assert_eq!(empty.into_iter().sum_::<i32>(), 0);

The same substitution runs through the *_or_default family. C# FirstOrDefault/LastOrDefault return default(T) — 0 for int, null for a reference type — which is indistinguishable from a sequence that really contained 0. first_or_default, last_or_default and return Option<T> instead. If you want C#'s "supply a fallback" shape, use first_or / last_or.

single_or_default returns a Result; C# throws on 2+ elements

C# SingleOrDefault substitutes the default only for the empty case and throws InvalidOperationException when the sequence has more than one element (SingleOrDefault: "this method throws an exception if there is more than one element in the sequence").

This crate takes the third option: neither a silent default nor a panic, but a value that says which happened. Absent stays ordinary; ambiguous becomes an error you have to handle.

use linq_rs::{LinqExt, SingleError};

assert_eq!(vec![1].into_iter().single_or_default(), Ok(Some(1)));
assert_eq!(Vec::<i32>::new().into_iter().single_or_default(), Ok(None));
assert_eq!(vec![1, 2].into_iter().single_or_default(), Err(SingleError::MoreThanOne));

// `try_single` distinguishes all three outcomes.
assert_eq!(vec![1].into_iter().try_single(), Ok(1));
assert_eq!(Vec::<i32>::new().into_iter().try_single(), Err(SingleError::Empty));
assert_eq!(vec![1, 2].into_iter().try_single(), Err(SingleError::MoreThanOne));

An earlier version returned None for both empty and too-many, so a caller could not tell "not found" from a broken uniqueness assumption. If you want that collapsing behaviour back it is one call: .single_or_default().ok().flatten().

If you want C#'s exact shape, single() panics on both cases and single_or(default) matches the .NET 6+ SingleOrDefault(defaultValue) overload — default for empty, panic for 2+.

max_by_key_ breaks ties toward the last element; C# MaxBy keeps the first

C# MaxBy replaces its running best only on a strictly-greater key (Max.cs: if (comparer.Compare(nextKey, key) > 0)), so the first element with the maximum key wins. Iterator::max_by_key, which max_by_key_ delegates to, documents the opposite: "If several elements are equally maximum, the last element is returned."

use linq_rs::LinqExt;

let tied = vec![("first", 5), ("second", 5)];
assert_eq!(tied.into_iter().max_by_key_(|(_, k)| *k), Some(("second", 5)));

// min_by_key_ agrees with C# MinBy: the first minimum wins.
let tied = vec![("first", 5), ("second", 5)];
assert_eq!(tied.into_iter().min_by_key_(|(_, k)| *k), Some(("first", 5)));

Porting a MaxBy whose result you care about on ties? Reverse the sequence first, or key on (key, Reverse(index)).

into_hashmap keeps the last duplicate; ToDictionary throws

C# ToDictionary raises ArgumentException when "keySelector produces duplicate keys for two elements" (ToDictionary). into_hashmap is HashMap::insert in a loop, so a later duplicate silently overwrites an earlier one.

use linq_rs::LinqExt;

let m = vec![("a", 1), ("a", 2), ("b", 3)].into_iter().into_hashmap(|(k, _)| *k);
assert_eq!(m.len(), 2);              // C#: ArgumentException
assert_eq!(m["a"], ("a", 2));        // last one wins

Use into_lookup when the keys are genuinely one-to-many; it keeps every value.

sum_ overflow is profile-dependent; C# Sum always throws

Enumerable.Sum(IEnumerable<int>) documents OverflowException — "The sum is larger than Int32.MaxValue" (Sum) — and it throws regardless of the caller's checked/unchecked context. sum_ and sum_by are Iterator::sum, which follows Rust's arithmetic profile: panic with debug-assertions = on, two's-complement wraparound in a default release build. vec![i32::MAX, 1].sum_::<i32>() panics under cargo test and produces -2147483648 under cargo build --release.

There is no checked variant here. If the totals can approach the type's range, sum into a wider type (sum_by(|x| x as i64)) or fold with checked_add yourself. The same applies to linq_rs::range: C# Enumerable.Range throws ArgumentOutOfRangeException when start + count - 1 exceeds Int32.MaxValue (Range), while range(i32::MAX - 1, 5) panics in debug and wraps past i32::MIN in release.

average diverges for a second reason: C# Average over int accumulates in long and throws on overflow, whereas average projects every element to f64, so sums beyond 2^53 lose precision instead of failing.

String ordering is byte-ordinal; C# is culture-aware

C# OrderBy "compares keys by using the default comparer Comparer<T>.Default" (OrderBy), which for string routes to String.CompareTo, and that method "performs a word (case-sensitive and culture-sensitive) comparison using the current culture" — it even treats ignorable characters such as a soft hyphen as absent (String.CompareTo). order, order_by and then_by use Rust's Ord, which for str is a lexicographic comparison of UTF-8 bytes. Case and punctuation therefore sort differently, and the result does not depend on the machine's locale.

use linq_rs::LinqExt;

let sorted: Vec<_> = vec!["apple", "Banana", "cherry"]
    .into_iter()
    .order()
        .collect();

// Byte order: every uppercase letter precedes every lowercase one.
assert_eq!(sorted, ["Banana", "apple", "cherry"]);
// C# `OrderBy(s => s)` under an en-US culture yields ["apple", "Banana", "cherry"].

Both are stable sorts, so ties keep source order in either language (OrderBy: "This method performs a stable sort").

count_by and aggregate_by yield in hash order; C# preserves first appearance

C# CountBy yields its key/count pairs in the order the keys first appear — the documented example prints IT, Sales, HR, the order those departments first occur in the input. Same for GroupBy, whose groups "are yielded in an order based on the order of the elements in source that produced the first key" (GroupBy).

group_by_key and into_lookup do match that: they carry an auxiliary index so groups come out in first-appearance order. count_by and aggregate_by do not — they iterate a HashMap directly, and std's HashMap iteration order is unspecified and varies run to run.

use linq_rs::LinqExt;

let mut counts: Vec<_> = vec!["ant", "bee", "ape"]
    .into_iter()
    .count_by(|w| w.chars().next().unwrap())
    .collect();
counts.sort();                       // required: the raw order is arbitrary
assert_eq!(counts, [('a', 2), ('b', 1)]);

// group_by_key needs no sort — first-appearance order, like C# GroupBy.
let keys: Vec<_> = vec!["ant", "bee", "ape"]
    .into_iter()
    .group_by_key(|w| w.chars().next().unwrap())
    .map(|g| g.into_parts().0)
    .collect();
assert_eq!(keys, ['a', 'b']);

Curiously, the *_partial_eq escape hatches for these two do preserve source order, because a linear scan has nowhere else to put the keys. Do not rely on that; it is a side effect of the algorithm, not a guarantee.

Work happens at call time, not on first MoveNext

Every C# operator listed here is documented as "implemented by using deferred execution … not executed until the object is enumerated" — including the ones that must buffer, such as OrderBy and Reverse. A C# query that is built and never enumerated costs nothing.

In this crate the eager operators do their work when they are called, not on first next() as C# does. The full classification is generated above under Evaluation timing and asserted by tests/laziness.rs; it is not restated here, because a second copy would drift (D-016).

Operators with no C# counterpart

Three convenience methods here are named after things that are not on System.Linq.Enumerable at all. They are kept because they are useful, but do not go looking for them in the C# docs:

All three operators that previously appeared here — for_each_, element_at_or and zip3 — named C# methods or overloads that do not exist, and all three were cut by D-019 for a different reason: none of them names a SQL concept. The lesson survives them: ForEach is List<T>.ForEach not LINQ, ElementAtOrDefault has no fallback-value overload, and Zip's three-sequence overload takes no selector.

Verified against the Enumerable method list.

Finally, none of the 38 IEqualityComparer / IComparer overloads are implemented, deliberately (D-202). Rust expresses "compare these differently" with traits and newtypes rather than a runtime comparer argument; the honest substitute is the *_by key-selector family.

Versioning

This crate follows Semantic Versioning. Some project-specific clarifications:

  • Adding a new method to LinqExt is treated as a minor bump, not a breaking change. Technically a new method could shadow a user's own extension method on Iterator, but the extension-trait pattern in the Rust ecosystem (itertools, tokio-stream, etc.) treats this as additive. If you derive your own trait methods and want isolation, name them explicitly with the full path.
  • Adding a new variant to a public enum or a new public field is a breaking change.
  • Tightening a trait bound on an existing method is a breaking change.
  • Loosening a trait bound (e.g. Eq + Hash + Clone → Eq + Hash) is a minor bump.
  • Renaming an operator is always breaking, even for ergonomic fixes.
  • *_partial_eq variants are independent operators — changing their signature is breaking just like the default ones.
  • Pre-1.0: anything can break in a minor bump. 0.1.x → 0.2.x may include breaking changes; 0.1.x → 0.1.y (patch) will not.

Design Notes

Evaluation timing

Measured, not asserted: a counting source records how many elements each operator pulls when it is called, before anything is iterated. tests/laziness.rs re-runs these measurements, so this table cannot drift from the code.

Lazy (10) — pull nothing at call time and stream during iteration:

distinct, distinct_by, distinct_by_partial_eq, distinct_partial_eq, select, select_many, skip_, take_, union_, where_.

Eager at call (19) — drain the source when called, before any iteration. C# defers these to the first MoveNext, so a query that is built and then discarded costs nothing there and costs full price here:

aggregate_by, aggregate_by_partial_eq, count_by, count_by_partial_eq, group_by_key, group_by_key_partial_eq, group_by_with_element, group_by_with_result, group_join, group_join_partial_eq, inner_join, inner_join_partial_eq, order, order_by, order_by_descending, order_by_with, order_descending, union_by, union_partial_eq.

Half-eager (6) — the receiver streams, but the argument is drained at call time even if the result is never iterated:

except, except_by, except_partial_eq, intersect, intersect_by, intersect_partial_eq.

Terminal (27) — consume and return a value, immediate by definition. Many still short-circuit: first pulls one element, any_ stops at the first match, try_single pulls at most two.

Generated by .github/scripts/gen-docs.py. Do not edit by hand.

Everything else

  • Zero dependencies — only std. Not even a dev-dependency; the interop check against itertools builds a throwaway crate in CI instead.
  • Naming — methods that would shadow a std::iter::Iterator method or a Rust keyword carry a trailing _ (where_, take_, skip_, any_). Where familiarity to C# and idiomatic Rust conflict, idiom wins.
  • size_hint / ExactSizeIterator / DoubleEndedIterator — propagated through the lazy adaptors where they can be given honestly (Select, Skip, Take, Concat, Zip, Reverse, Chunk, DefaultIfEmpty, SkipLast). The unpredictable ones are left at the default rather than lying.
  • FusedIterator — implemented on fourteen adaptors, conditionally on the source except Reverse and Chunk, which are unconditional.

License

Dual-licensed under either of

at your option. This is the Rust ecosystem norm (D-012).

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this crate by you shall be dual licensed as above, without any additional terms or conditions.

Note: 0.1.0 was published MIT-only and stays that way. A published version's licence cannot be changed retroactively; the dual licence begins at 0.2.0.