C# Linq vs. Python7 avril 2011

Tests / Performance

Voici un petit récapitulatif des principales fonctionnalités de C# - Linq et leur équivalence Python.

Dans les exemples qui vont suivre, « l » représente un type IEnumerable<T> en C# et un iterable quelconque en Python.

Considérons également que les éléments constitutifs des listes traitées sont des objets ayant les attributs suivants : Value (entier), Description (chaîne) et Etat (booléen).

FonctionExpression LinqRé-écriture en Python
Selectvar r = l.Select(e => e.Value);r = map(lambda e: e.Value, l)
ou
r = list(e.Value for e in l)
Wherevar r = l.Where(e => e.Value == 5).Select(e => e.Description);r = list(e.Description for e in l if e.Value == 5)
ToDictionaryvar r = l.ToDictionary(e => e.Value);r = dict(list((e.Value, e) for e in l))
Distinctvar r = l.Select(e => e.Value).Distinct();r = dict(list((e.Value,None) for e in l)).keys()
GroupByvar r = l.GroupBy(e => e.Etat).Select(g => new { Nom = g.Key, Count = g.Count() });r = dict(list((e.Etat,len(list(ee for ee in l if ee.Etat == e.Etat))) for e in l))
ou
r = dict(list((e.Etat,list(ee.Etat for ee in l).count(e.Etat)) for e in l))

Sources :