FAQ - Help and questions

What is the Rust equivalent of C# LINQ?

#porting#csharp#iteratorspublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Iterator adapters in the standard library cover LINQ's common operators: filter for Where, map for Select, sum and count, any and all, find for FirstOrDefault, flat_map for SelectMany. Iterators are lazy like LINQ. Sorting and grouping need a collection, so they use sort_by and a HashMap.

Checked with rustc 1.93.0, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

Call .iter() on a collection and chain adapters; end the chain with a consumer such as sum, collect, count or find. Nothing runs until the consumer runs, as with LINQ's deferred execution. The program below does eight typical LINQ queries and compiled and ran with rustc 1.93.0.

LINQRust
Wherefilter
Selectmap
Sum, Countsum, count
Any, Allany, all
FirstOrDefault(pred)find(pred) (returns Option)
SelectManyflat_map
Take, Skiptake, skip
Zip, index in Select((x, i) => ...)zip, enumerate
Distinctcollect into a HashSet
OrderBy, OrderByDescendingsort_by on a Vec (not lazy)
GroupBya HashMap with entry
ToList, ToDictionarycollect::<Vec<_>>(), collect::<HashMap<_, _>>()
src/main.rsrust
use std::collections::{HashMap, HashSet};

#[derive(Debug, Clone)]
struct Order {
    customer: &'static str,
    total: f64,
    paid: bool,
}

fn main() {
    let orders = vec![
        Order { customer: "ada", total: 30.0, paid: true },
        Order { customer: "bo", total: 12.5, paid: false },
        Order { customer: "ada", total: 7.5, paid: true },
        Order { customer: "cy", total: 99.0, paid: true },
    ];

    // orders.Where(o => o.Paid).Select(o => o.Total).Sum()
    let paid: f64 = orders.iter().filter(|o| o.paid).map(|o| o.total).sum();
    // orders.Any(o => !o.Paid)      orders.All(o => o.Total > 0)
    let unpaid = orders.iter().any(|o| !o.paid);
    let positive = orders.iter().all(|o| o.total > 0.0);
    // orders.OrderByDescending(o => o.Total).Take(2)   (sorting needs a Vec)
    let mut sorted = orders.clone();
    sorted.sort_by(|a, b| b.total.total_cmp(&a.total));
    let top: Vec<_> = sorted.iter().take(2).map(|o| o.customer).collect();
    // orders.GroupBy(o => o.Customer).ToDictionary(g => g.Key, g => g.Sum(o => o.Total))
    let mut by_customer: HashMap<&str, f64> = HashMap::new();
    for o in &orders {
        *by_customer.entry(o.customer).or_default() += o.total;
    }
    // orders.Select(o => o.Customer).Distinct().Count()
    let distinct = orders.iter().map(|o| o.customer).collect::<HashSet<_>>().len();
    // orders.FirstOrDefault(o => o.Total > 50)
    let big = orders.iter().find(|o| o.total > 50.0).map(|o| o.customer);
    let pairs: Vec<(usize, &str)> = orders.iter().map(|o| o.customer).enumerate().collect();
    let letters: Vec<char> = orders.iter().flat_map(|o| o.customer.chars()).collect();

    println!("{paid} {unpaid} {positive} {top:?} {distinct} {big:?}");
    let mut totals: Vec<_> = by_customer.into_iter().collect();
    totals.sort_by(|a, b| a.0.cmp(b.0));
    println!("{totals:?} {} {}", pairs.len(), letters.len());
}
text
136.5 true true ["cy", "ada"] 3 Some("cy")
[("ada", 37.5), ("bo", 12.5), ("cy", 99.0)] 4 10

Common mistakes#

  • Forgetting the consumer. An iterator chain that ends in map(...) does nothing by itself.
  • Expecting HashMap to keep insertion order. Sort the result, as above, when the order matters.
  • Using sort on f64. Floats are not totally ordered; use sort_by with total_cmp.

Are iterator chains slower than a for loop?#

In optimised builds they compile to the same kind of loop; measure with cargo build --release before assuming a difference.

Is there a crate with more operators?#

Yes, the itertools crate adds grouping, joining and windowing helpers.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet