C# IEnumerable<T> 分批次返回

发布时间 2024-01-10 18:24:07作者: WmW

有的时候数据源是IEnumerable<T>,返回的数据可能有几百万条,咱们既不能等其几百万条都迭代完了后再保存(内存顶不住),也不能来一条就保存一条(cpu亚历山大),

希望能分批次的保存,比如等其每次枚举1000条,然后统一保存一下,于是我就写了2个IEnumerable<T>的分批扩展方法,一个基于条数,一个基于数据的预估字节数

        /// <summary>
        /// 将枚举的数据按照每批次size条枚举返回
        /// </summary>
        /// <typeparam name="T">要枚举的数据泛型</typeparam>
        /// <param name="values">要枚举的数据</param>
        /// <param name="size">每批的数量</param>
        /// <returns>最多size条数据的集合</returns>
        public static IEnumerable<List<T>> ToBatch<T>(this IEnumerable<T> values, int size) {
            List<T> list = new List<T>();
            foreach (var val in values) {
                list.Add(val);
                if (list.Count == size) {
                    yield return list;
                    list.Clear();
                }
            }
            yield return list;
        }
        /// <summary>
        /// 将枚举的数据按照每批次不超过maxByteLength字节枚举返回
        /// </summary>
        /// <typeparam name="T">要枚举的数据泛型</typeparam>
        /// <param name="values">要枚举的数据</param>
        /// <param name="getSizeFunc">每个数据的字节数</param>
        /// <param name="maxByteLength">每批次不超过的字节数</param>
        /// <returns>不超过maxByteLength字节数据的集合</returns>
        public static IEnumerable<List<T>> ToBatch<T>(this IEnumerable<T> values, Func<T, int> getSizeFunc, int maxByteLength = 1024 * 1024 * 8) {
            List<T> list = new List<T>();
            int byteLength = 0;
            foreach (var val in values) {
                int size = getSizeFunc(val);
                if (byteLength + size > maxByteLength) {
                    yield return list;
                    list.Clear();
                    byteLength = 0;
                }
                list.Add(val);
                byteLength += size;
            }
            yield return list;
        }