在C#泛型列表扩展 [英] Generic List Extensions in C#

查看:133
本文介绍了在C#泛型列表扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一些扩展,以模仿地图和减少Lisp语言功能

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?

推荐答案

这些看起来非常相似,在LINQ的扩展已经:

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 */);



为什么第二个例子称为转换?你打算以某种方式更改列表中的值?如果是这样的情况下,你可以使用会更好 ConvertAll< T> 选择< T>

这篇关于在C#泛型列表扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆