使用LINQ將集合拆分為‘N’部件?有什么好辦法把一個集合分割成n和LINQ的零件?當然也不一定均衡。也就是說,我想將集合劃分為子集合,每個子集合都包含元素的子集,其中最后一個集合可以是粗糙的。
3 回答
揚帆大魚
TA貢獻1799條經驗 獲得超9個贊
static class LinqExtensions{
public static IEnumerable<IEnumerable<T>> Split<T>(this IEnumerable<T> list, int parts)
{
int i = 0;
var splits = from item in list
group item by i++ % parts into part select part.AsEnumerable();
return splits;
}}
胡子哥哥
TA貢獻1825條經驗 獲得超6個贊
沒有昂貴的乘法、除法或模運算符 所有操作均為O(1)(見下文注) 為IEnumerable<>源代碼工作(不需要計數屬性) 簡約
public static IEnumerable<IEnumerable<T>>
Section<T>(this IEnumerable<T> source, int length){
if (length <= 0)
throw new ArgumentOutOfRangeException("length");
var section = new List<T>(length);
foreach (var item in source)
{
section.Add(item);
if (section.Count == length)
{
yield return section.AsReadOnly();
section = new List<T>(length);
}
}
if (section.Count > 0)
yield return section.AsReadOnly();}myEnum.Section(myEnum.Count() / number_of_sections + 1)
- 3 回答
- 0 關注
- 441 瀏覽
添加回答
舉報
0/150
提交
取消
