C#中的通用映射/减少列表扩展 [英] Generic Map/Reduce List Extensions in C#
本文介绍了C#中的通用映射/减少列表扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
public delegate R ReduceFunction< T, R(T t,R前一个);
public delegate void TransformFunction< T>(T t,params object [] args);
public static R Reduce< T,R>(这个List< T>列表,ReduceFunction< T,R> r,R initial)
{
var aggregate = initial;
foreach(列表中的变量)
aggregate = r(t,aggregate);
return aggregate;
public static void Transform< T>(this List< T> list,TransformFunction< T> f,params object [] args)
{
foreach列表)
f(t,args);
$ / code>
转换函数将减少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 etc
Does 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>
.
这篇关于C#中的通用映射/减少列表扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文