說明:
針對長度較大的List物件,可以分組批量進行處理, 如:長度為1000的List
Source
/******************************************************************************
* 名稱:List分組迭代器
* 說明:針對長度較大的List物件,可以分組批量進行處理
* 如:長度為1000的List<int>物件,可分為10組,每組100條,對資料進行業務邏輯處理
* 作者:Sybs
* 時間:2018-10-15
* **************************************************************************/
namespace System.Collections.Generic
{
/// <summary>
/// List分組迭代器
/// </summary>
public class ListGroupIterator<T>
{
private int _groupsize = 1;
/// <summary>
/// 分組大小(預設值為1)
/// </summary>
public int GroupSize
{
get => _groupsize;
set => _groupsize = value < 1 ? 1 : value;
}
/// <summary>
/// 分組數量
/// </summary>
public int GroupCount { get => (Source.Count + GroupSize - 1) / GroupSize; }
/// <summary>
/// List資料來源
/// </summary>
public List<T> Source { get; set; }
public ListGroupIterator() { }
public ListGroupIterator(int groupSize) : this(groupSize, null) { }
public ListGroupIterator(List<T> list) : this(1, list) { }
public ListGroupIterator(int groupSize, List<T> list)
{
this.GroupSize = groupSize;
this.Source = list;
}
/// <summary>
/// ListGroupIterator迭代器
/// </summary>
/// <returns></returns>
public IEnumerator<List<T>> GetEnumerator()
{
if (Source?.Count > 0)
{
var ps = Convert.ToInt32(Math.Ceiling(Source.Count * 1.0d / GroupSize));
var model = Source.Count % GroupSize;
for (int i = 0; i < ps; i++)
{
var len = ps - i == 1 && model > 0 ? model : GroupSize;
yield return Source.GetRange(GroupSize * i, len);
}
}
}
/// <summary>
/// 將List<T>例項賦值給ListGroupIterator物件
/// </summary>
/// <param name="list"></param>
public static implicit operator ListGroupIterator<T>(List<T> list)
{
return new ListGroupIterator<T> { Source = list };
}
}
}
呼叫
using System;
using System.Collections.Generic;
namespace Demo
{
class Program
{
static void Main()
{
ListGroupIterator<int> lg1 = new List<int>() { 1, 2, 3, 4, 5 };
ListGroupIterator<int> lg2 = new ListGroupIterator<int>(new List<int> { 1, 2, 3, 4, 5 });
ListGroupIterator<int> lg3 = new ListGroupIterator<int>(3, new List<int>() { 1, 2, 3, 4, 5 });
lg3.Source.AddRange(new List<int>() { 6, 7, 8, 9 });
lg3.GroupSize = 2;
foreach (var item in lg3) { Console.WriteLine(string.Join(",", item)); }
Console.ReadLine();
}
}
}