Split a List into smaller lists of N size

前端 未结 17 1780
后悔当初
后悔当初 2020-11-22 16:55

I am attempting to split a list into a series of smaller lists.

My Problem: My function to split lists doesn\'t split them into lists of the correct

17条回答
  •  执念已碎
    2020-11-22 17:44

    I have a generic method that would take any types include float, and it's been unit-tested, hope it helps:

        /// 
        /// Breaks the list into groups with each group containing no more than the specified group size
        /// 
        /// 
        /// The values.
        /// Size of the group.
        /// 
        public static List> SplitList(IEnumerable values, int groupSize, int? maxCount = null)
        {
            List> result = new List>();
            // Quick and special scenario
            if (values.Count() <= groupSize)
            {
                result.Add(values.ToList());
            }
            else
            {
                List valueList = values.ToList();
                int startIndex = 0;
                int count = valueList.Count;
                int elementCount = 0;
    
                while (startIndex < count && (!maxCount.HasValue || (maxCount.HasValue && startIndex < maxCount)))
                {
                    elementCount = (startIndex + groupSize > count) ? count - startIndex : groupSize;
                    result.Add(valueList.GetRange(startIndex, elementCount));
                    startIndex += elementCount;
                }
            }
    
    
            return result;
        }
    

提交回复
热议问题