Split List into Sublists with LINQ

前端 未结 30 2489
灰色年华
灰色年华 2020-11-21 06:26

Is there any way I can separate a List into several separate lists of SomeObject, using the item index as the delimiter of each s

30条回答
  •  青春惊慌失措
    2020-11-21 06:54

    Old code, but this is what I've been using:

        public static IEnumerable> InSetsOf(this IEnumerable source, int max)
        {
            var toReturn = new List(max);
            foreach (var item in source)
            {
                toReturn.Add(item);
                if (toReturn.Count == max)
                {
                    yield return toReturn;
                    toReturn = new List(max);
                }
            }
            if (toReturn.Any())
            {
                yield return toReturn;
            }
        }
    

提交回复
热议问题