LINQ分区列表分为8个成员的列表

一个人如何使用LINQ来获取一个列表并将其分解为一个列表列表,从而在每第8个条目上对原始列表进行分区?

我想像这样的事情会涉及“跳过”和/或“接听”,但是我对LINQ还是很陌生。

编辑:使用C#/ .Net 3.5

Edit2:该问题的措词与其他“重复”问题不同。尽管问题相似,但该问题的答案更好:“接受的”答案非常可靠(带有yield陈述),以及乔恩·斯凯特的建议使用MoreLinq(“其他”问题中不建议)。有时重复是好的,因为重复会迫使您重新检查问题。


慕娘9325324
浏览 584回答 3
3回答

慕田峪9158850

使用以下扩展方法将输入分成子集public static class IEnumerableExtensions{&nbsp; &nbsp; public static IEnumerable<List<T>> InSetsOf<T>(this IEnumerable<T> source, int max)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; List<T> toReturn = new List<T>(max);&nbsp; &nbsp; &nbsp; &nbsp; foreach(var item in source)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; toReturn.Add(item);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (toReturn.Count == max)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; yield return toReturn;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; toReturn = new List<T>(max);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if (toReturn.Any())&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; yield return toReturn;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}

德玛西亚99

在MoreLINQ中,我们有这样一种方法作为Batch方法:// As IEnumerable<IEnumerable<T>>var items = list.Batch(8);要么// As IEnumerable<List<T>>var items = list.Batch(8, seq => seq.ToList());
打开App,查看更多内容
随时随地看视频慕课网APP