C# Split List

Unity3D/C# 2019. 1. 22. 15:35
반응형


리스트에 들어있는 값들을 5개씩 나누어 담고 싶다 


1
2
3
4
5
6
public IEnumerable<IEnumerable<T>> Batch<T>(IEnumerable<T> items, int maxItems)
    {
        return items.Select((item, index) => new { item, index })
                    .GroupBy(x => x.index / maxItems)
                    .Select(g => g.Select(x => x.item));
    }
cs


참고: https://stackoverflow.com/questions/11463734/split-a-list-into-smaller-lists-of-n-size




직접구현하면 벌어지는일;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public IEnumerable<IEnumerable<T>> SplitList<T> (IEnumerable<T> source, int size) {
        var e = source.GetEnumerator();
        int cnt = 0;
        List<List<T>> parentList = new List<List<T>>();
        List<T> childList = null;
        while (e.MoveNext())
        {
            Debug.Log(e.Current);
            if (cnt % size == 0)
            {
                childList = new List<T>();
                parentList.Add(childList);
            }
            childList.Add(e.Current);
            cnt++;
        }
        return parentList;
    }
cs


반응형

'Unity3D > C#' 카테고리의 다른 글

C# Event & delegate  (0) 2019.01.23
ReSharper  (0) 2019.01.23
What and where are the stack and heap?  (0) 2019.01.18
Visual Studio Code 에서 Newtonsoft.JSON 사용하기  (0) 2018.12.28
Visual Studio Code 에서 C# 콘솔 프로젝트 하기  (0) 2018.12.28
: