Abschluss: Ein Inventar portieren
Lektion 47 von 48 im Kurs C# für Rust-Entwickler von Coddy.
Aufgabe
EinfachPortiere il riferimento sorgente in C#. Due righe contengono nomi ASCII separati da virgole e altrettante variazioni intere. Una prima riga vuota significa che entrambe le sequenze sono vuote. Rimuovi gli spazi iniziali e finali dai nomi e convertili in minuscolo, ignora i nomi vuoti, somma le variazioni, scarta i totali minori o uguali a zero, quindi ordina per nome in base all'ordine ordinale. I nomi contengono solo lettere, spazi, cifre e trattini bassi. Restituisci le voci nome:totale unite da virgole; il driver antepone items:.
Modifica i file C# sbloccati. Il file bloccato visibile Main.cs legge le righe descritte, chiama Exercise.Solve, verifica che l'input non sia stato modificato e stampa il risultato con un solo carattere di nuova riga finale. Mantieni le API dichiarate. Non aggiungere un secondo Main né stampare output diagnostico.
Programma di riferimento Rust
use std::collections::BTreeMap;
fn inventory(names: &[&str], changes: &[i32]) -> String {
let mut totals: BTreeMap<String, i32> = BTreeMap::new();
for (name, change) in names.iter().zip(changes) {
let key = name.trim().to_ascii_lowercase();
if !key.is_empty() {
*totals.entry(key).or_insert(0) += change;
}
}
totals
.iter()
.filter(|(_, total)| **total > 0)
.map(|(name, total)| format!("{}:{}", name, total))
.collect::<Vec<_>>()
.join(",")
}
fn main() {
println!("items:{}", inventory(&[" Tea ", "tea", "cake"], &[2, 3, -1]));
}
Probier es selbst
using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
public class Program {
static int I(string text) { return int.Parse(text,CultureInfo.InvariantCulture); }
static int[] Ints(string text) { return text.Length==0 ? new int[0] : text.Split(',').Select(I).ToArray(); }
static string[] Words(string text) { return text.Length==0 ? new string[0] : text.Split(','); }
static string Snapshot(object value) { if (value==null) return "<null>"; if (value is string) return (string)value; var sequence=value as System.Collections.IEnumerable; if (sequence!=null) { var items=new List<string>(); foreach (object item in sequence) items.Add(Snapshot(item)); return string.Join("|",items); } return Convert.ToString(value,CultureInfo.InvariantCulture); }
public static void Main() {
System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;
var rows = new List<string>(); string line; while ((line=Console.ReadLine()) != null) rows.Add(line);
string[] input=rows.ToArray();
var a0 = Words(input[0]); string before0=Snapshot(a0);
var a1 = Ints(input[1]); string before1=Snapshot(a1);
var result = Exercise.Solve(a0,a1);
if (Snapshot(a0) != before0) throw new Exception("Input mutation");
if (Snapshot(a1) != before1) throw new Exception("Input mutation");
Console.WriteLine("items:" + result);
}
}
Alle Lektionen in C# für Rust-Entwickler
1Hier geht’s los
Führe dein erstes C#-Programm aus4Schleifen und Sequenzen
Arrays und GrenzenIndizierte for-Schleifenforeach, break und continueListen und sichere AktualisierungenRückblick: Positives Präfix7Zuverlässige C#-Module
Gezielte AusnahmebehandlungNamespaces und DateienWert- und ReferenzsemantikDeterministische RessourcenfreigabeRückblick: Gültige Zahlen importieren10Projekt: Bestellpipeline
Projekt: BestellmodellProjekt: Zeilen validieren2C#-Werte und Text
Ausgabe, Kommentare und MainTypen, var und ZuweisungenGanzzahl- und DezimalrechnungStrings, char und FormatierungParsen ohne AusnahmenRückblick: Belegzeile5Sammlungen und Abfragen
Dictionaries und fehlende SchlüsselSets und MitgliedschaftLINQ-Filter und ProjektionenSortieren ohne VeränderungRückblick: Wortbestand3Entscheidungen und fehlende Werte
Boolesche Logik und GleichheitVerzweigungen und frühe RückgabenEnums und switchNullable-Werte und StandardwerteRückblick: ZugriffsentscheidungÜbe selbstständig: Online-C#-Compiler