C#学习教程:C#:更改数组中每一项的值基于提供的委托每个值的结果。例如,如果我有一个数组{1,2,3}和一个返回每个值的平方的委托,我希望能够运行一个接受数组和委托并返回{1,4,9}。有这样的事吗?我不知道(替换每个元素而不是转换为新的数组或序列),但它很容易编写:publicstaticvoidConvertInPlace(thisIListsource,Funcprojection){for(inti=0;iuse:int[]values={1,2,3};values.ConvertInPlace(x=>x*x);当然,如果您不需要更改现有数组,使用Select发布的其他答案将更加实用。或者.NET2中已有的ConvertAll方法:int[]values={1,2,3};values=Array.ConvertAll(values,x=>x*x);这都是假设一个一维数组.如果你想包含矩形数组,它会变得更棘手,特别是如果你想避免装箱。LINQ通过Select扩展方法提供对投影的支持:varnumbers=new[]{1,2,3};varsquares=numbers.Select(i=>i*i).ToArray();您还可以使用稍微不太平滑的Array.ConvertAll方法:varsquares=Array.ConvertAll(numbers,i=>i*i);您可以通过以下方式处理锯齿嵌套投影数组:varnumbers=new[]{new[]{1,2},new[]{3,4}};varsquares=数字。Select(i=>i.Select(j=>j*j).ToArray()).ToArray();多维数组有点复杂。我编写了以下扩展方法,它投影多维数组中的每个元素,而不考虑其等级。staticArrayConvertAll(thisArraysource,Converterprojection){if(!typeof(TSource).IsAssignableFrom(source.GetType().GetElementType())){抛出新的ArgumentException();}vardims=Enumerable.Range(0,source.Rank).Select(dim=>new{lower=source.GetLowerBound(dim),upper=source.GetUpperBound(dim)});var结果=Array.CreateInstance(typeof(TResult),dims.Select(dim=>1+dim.upper-dim.lower).ToArray(),dims.Select(dim=>dim.lower).ToArray());varindices=dims.Select(dim=>Enumerable.Range(dim.lower,1+dim.upper-dim.lower)).Aggregate((IEnumerable>)null,(total,current)=>total!=null?total.SelectMany(item=>当前,(existing,item)=>existing.Concat(new[]{item})):current.Select(item=>(IEnumerable)new[]{item})).Select(index=>index.ToArray());foreach(varindexinindices){varvalue=(TSource)source.GetValue(index);结果.SetValue(投影(值),索引);}返回结果;}上面描述的方法可以使用等级3的数组进行测试,像这样:varsource=newint[2,3,4];for(vari=source.GetLowerBound(0);i(i=>i*i);for(vari=source.GetLowerBound(0));i使用System.Linq,您可以执行以下操作:varnewArray=arr.Select(x=>myMethod(x)).ToArray();LINQ查询可以轻松地为您处理此问题-确保您引用System.Core.dll并具有usingSystem.Linq;声明例如,如果您的数组位于一个名为numberArray的变量,以下代码将为您提供所需的内容:一个数组而不是一个IEnumerable。您可以使用linq以简写方式执行此操作,但要小心记住它无论如何都会在下面发生foreach.int[]x={1,2,3};x=x.Select((Y)=>{returnY*Y;}).ToArray();这是MxNarrays的另一种解决方案,其中M和N在编译时是未知的。以上就是C#学习教程:C#:改变数组中每一项的值。如果对大家有用,需要详细了解C#学习教程,希望大家多多关注---//credit:https://blogs.msdn.microsoft.com/ericlippert/2010/06/28/computing-a-cartesian-product-with-linq/publicstaticIEnumerable>CartesianProduct(IEnumerable>sequences){IEnumerable>result=new[]{Enumerable.Empty()};foreach(varsequenceinsequences){//收到关于不同编译器行为的警告//在闭包中访问序列vars=sequence;结果=result.SelectMany(seq=>s,(seq,item)=>seq.Concat(new[]{item}));}返回结果;}publicstaticvoidConvertInPlace(thisArrayarray,Funcprojection){if(array==null){return;}//建立每个维度的范围vardimensions=Enumerable.Range(0,array.Rank).Select(r=>Enumerable.Range(0,array.GetLength(r)));//建立所有可能索引的列表varindexes=EnumerableHelper.CartesianProduct(dimensions).ToArray();foreach(varindexinindexes){varcurrentIndex=index.ToArray();array.SetValue(投影(array.GetValue(currentIndex)),currentIndex);}}本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如有转载请注明出处:
