当前位置: 首页 > 编程语言 > C#

将C#集合拆分为相等的部分,保持排序分享

时间:2023-04-10 23:31:45 C#

将C#集合拆分为相等的部分,保持排序对集合进行排序。我尝试使用以下扩展方法,但它错误地破坏了它们。基本上,如果我要查看集合中的项目,与合并的分解集合相比,顺序应该相同。这是我正在使用但不起作用的代码:publicstaticIEnumerableSplit(thisIEnumerablelist,intparts){inti=0;varsplits=fromnameinlistgroupnamebyi++%partsintopartselectpart.AsEnumerable();回归分裂;我不得不利用这一点来比较4组中的对象列表……它会使对象按照它们最初的顺序排列。可以扩展为除“列表”之外的其他内容//////将元素列表划分为更小的元素组///////////////publicstaticList[]Partition(Listlist,inttotalPartitions){if(list==null)抛出newArgumentNullException("list");如果(totalPartitions[]partitions=newList[totalPartitions];intmaxSize=(int)Math.Ceiling(list.Count/(double)totalPartitions);intk=0;for(inti=0;i();for(intj=k;j=list.Count)break;partitions[i].Add(list[j]);}k+=maxSize;}returnpartitions;}一个稍微干净的LINQ方法来解决这个相当古老的问题:publicstaticIEnumerable>Partition(thisIEnumerablesource,intn){varcount=source.Count();返回源.Select((x,i)=>new{value=x,index=i}).GroupBy(x=>x.index/(int)Math.Ceiling(count/(double)n)).Select(x=>x.Select(z=>z.value));}JonSkeet的MoreLINQ库可能对您有所帮助:https://code.google.com/p/morelinq/source/browse/MoreLinq/Batch.csvaritems=list.Batch(parts);//给你IEnumerable>varitems=list.Batch(parts,seq=>seq.ToList());//给你IEnumerable>//等等...另一个例子:publicclassProgram{staticvoidMain(string[]args){varlist=newList();for(inti=1;i当我扫描批次的内容时,顺序被保留doublepartLength=list.Count()/(double)parts;inti=0;varsplits=fromnameinlistgroupnamebyMath.Floor((double)(i++/partLength))intopartselectpart;据我所知,你想在不破坏元素顺序的情况下打破相同大小的几个部分的可枚举。看起来唯一的选择是首先你可以枚举输入的长度,所以你至少需要在枚举中进行两次迭代。/(double)parts);vargroups=Enumerable.Range(0,nGroups);returngroups.Select(g=>list.Skip(g*parts).Take(parts));}这将做你想要的.它还将满足不均匀的分组,即10组中的27个元素将产生7组,每组3个,每个3个publicstaticIEnumerable>SplitMaintainingOrder(thisIEnumerablelist,intparts){if(list.Count()==0)returnEnumerable.Empty>();vartoreturn=newList>();varsplitFactor=Decimal.Divide((decimal)list.Count(),parts);intcurrentIndex=0;对于(vari=0;i0)?Math.Floor(splitFactor):Math.Ceiling(splitFactor)));toreturn.Add(list.Skip(currentIndex).Take(toTake));currentIndex+=toTake;返回返回;}出于演示目的[TestMethod]publicvoidsplitlist(){varlist=newdecimal[]{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27};varsplitlists=list.SplitMaintainingOrder(10);诠释我=1;foreach(vargroupinsplitlists){Console.WriteLine("Group{0}elements{1}",i++,String.Join(",",group));}}上面的演示生成测试名称:splitlist测试结果:通过结果StandardOutput:第1组元素1,2,3第2组元素4,5第3组元素6,7,8第4组元素9,10,11第5组元素12,13第6组元素14,15,16第7组元素17,18,19第8组元素20,21第9组元素22,23,24第10组元素25,26,27要将一个泛型列表拆分成相等的块,使用下面的泛型方法以上是C#学习教程:将一个C#集合拆分成相等的部分,保持整个内容排序,如果对大家有用还需要了解更多关于C#学习教程,希望大家多多关注—privateIEnumerable>SplitMaintainingOrder(IEnumerablelist,intcolumnCount){varelementsCount=list.Count();introwCount=elementsCount/columnCount;intnoOfCells=elementsCount%columnCount;intfinalRowCount=rowCount;如果(noOfCells>0){finalRowCount++;}vartoreturn=newList>();varpushto=0;for(intj=0;j本文收集自网络,不代表立场,如涉及侵权,请点击右侧联系管理员删除。如需转载,请注明出处: