转换函数将减少cruft,如:
foreach(列表中的变量) if(条件&& moreconditions) //执行工作等这是否有意义?
解决方案这些看起来与Linq中的扩展非常相似:
//采用一个匹配Func< T,R>委托 listInstance.Aggregate( startingValue,(x,y)=> / *汇总两个后续值* /); //使用一个匹配Action< T>委托 listInstance.ForEach( x => / *用x * /做某事);为什么第二个例子叫做Transform?你打算改变列表中的值吗?如果是这种情况,您最好使用 ConvertAll< T> 或选择< T> 。
I am writing a few extensions to mimic the map and reduce functions in Lisp.
public delegate R ReduceFunction<T,R>(T t, R previous); public delegate void TransformFunction<T>(T t, params object[] args); public static R Reduce<T,R>(this List<T> list, ReduceFunction<T,R> r, R initial) { var aggregate = initial; foreach(var t in list) aggregate = r(t,aggregate); return aggregate; } public static void Transform<T>(this List<T> list, TransformFunction<T> f, params object [] args) { foreach(var t in list) f(t,args); }The transform function will cut down on cruft like:
foreach(var t in list) if(conditions && moreconditions) //do work etcDoes this make sense? Could it be better?
解决方案These look very similar to extensions in Linq already:
//takes a function that matches the Func<T,R> delegate listInstance.Aggregate( startingValue, (x, y) => /* aggregate two subsequent values */ ); //takes a function that matches the Action<T> delegate listInstance.ForEach( x => /* do something with x */);Why is the 2nd example called Transform? Do you intend to change the values in the list somehow? If that's the case you may be better off using ConvertAll<T> or Select<T>.