拆分C​​#集合分成相等的部分,保持排序 [英] Split C# collection into equal parts, maintaining sort

查看:103
本文介绍了拆分C​​#集合分成相等的部分,保持排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图集合分割成多个集合,同时保持了一种我对集合。我已经尝试使用下面的扩展方法试过,但它错误地打破他们。基本上,如果我是看集合中的项目,顺序应该相比,加入打散集合时是一样的。这里是code我使用不工作:

I am trying to split a collection into multiple collections while maintaining a sort I have on the collection. I have tried using the following extension method, but it breaks them incorrectly. Basically, if I was to look at the items in the collection, the order should be the same when compared to the broken up collections joined. Here is the code I am using that doesn't work:

public static IEnumerable<IEnumerable<T>> Split<T>(this IEnumerable<T> list, int parts)
        {
            int i = 0;
            var splits = from name in list
                         group name by i++ % parts into part
                         select part.AsEnumerable();
            return splits;
        }


  • INT部分=次级可枚举数

  • 推荐答案

    我不得不使用这个对象的名单在4组比较彼此...
    它将保持对象的顺序,原来拥有。可以扩大做多列表

    I had to make use of this to compare a list of objects to one another in groups of 4... it will keep the objects in the order that the original possessed. Could be expanded to do something other than 'List'

    /// <summary>
    /// Partition a list of elements into a smaller group of elements
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="list"></param>
    /// <param name="totalPartitions"></param>
    /// <returns></returns>
    public static List<T>[] Partition<T>(List<T> list, int totalPartitions)
    {
        if (list == null)
            throw new ArgumentNullException("list");
    
        if (totalPartitions < 1)
            throw new ArgumentOutOfRangeException("totalPartitions");
    
        List<T>[] partitions = new List<T>[totalPartitions];
    
        int maxSize = (int)Math.Ceiling(list.Count / (double)totalPartitions);
        int k = 0;
    
        for (int i = 0; i < partitions.Length; i++)
        {
            partitions[i] = new List<T>();
            for (int j = k; j < k + maxSize; j++)
            {
                if (j >= list.Count)
                    break;
                partitions[i].Add(list[j]);
            }
            k += maxSize;
        }
    
        return partitions;
    }
    

    这篇关于拆分C​​#集合分成相等的部分,保持排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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