闲来无事时积累的一些Linq函数,有时间就更新。
需要注意python版本如果低于3.0不支持lambda,只能单独写函数传参,比较麻烦
1.FirstOrDefault:
def FirstOrDefault(collection, func): result = filter(func, collection) if len(result) == 0: return None return result[0] def main(): def condition(m): return m < 3 print FirstOrDefault([1,2,3,4], condition) #print 1
返回1
2.Where:
def Where(collection, func): result = filter(func, collection) if len(result) == 0: return None return result def main(): def condition(m): return m < 3 print Where([1,2,3,4], condition) #print [1,2]
返回筛选后的数组1,2
3.Distinct:
def Distinct(collection, isContainFunc): resultList = list() for item in collection: def firstOrDefaultPredicate(m): return isContainFunc(m,item) containValue = FirstOrDefault(collection, firstOrDefaultPredicate) if containValue != None: if not item in resultList: resultList.append(item) return resultList def main(): tmp = [1,2,2,3,4,3] def compare(x,y):return x==y result = Distinct(tmp, compare) print result #print [1,2,3,4]
去重复,依赖FirstOrDefault。