C#中的通用映射/减少列表扩展

编程入门 行业动态 更新时间:2024-10-06 20:40:26
本文介绍了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#中的通用映射/减少列表扩展

本文发布于:2023-11-30 15:29:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1650513.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:列表

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!