PyQueryableList: LINQ's Queryable List for Python
Introduction
PyQueryableList is a quick attempt to duplicate some of Microsoft's LINQ IQueryable natively in Python.
The main class is QueryableList which extends UserList, and accepts data in the constructor.
QueryableList makes use of a decorator returns_new to enable method chaining.
Code
Usage
a = QueryableList(range(20)) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
b = a.take(10).where(lambda x: x < 5).order_by_descending() # Method chaining example
print b # [4, 3, 2, 1, 0]
print b.count() # 5
print b.count(lambda x: x < 2) # 2
print b.contains(4) # True
print b.contains(5) # False
print b.single() # 4
print b.single(lambda x: x < 3) # 2
print b.single_or_default(lambda x: x == 9) # None
try:
print b.single(lambda x: x == 9) # ValueError
except ValueError:
print "ValueError"
print b.sum() # 10
print b.sum(lambda x: x > 2) # 7
print b.average() # 2
Source
ejstembler/PyQueryableList