Sec*_*mon 19 c# loops list range
有没有办法使用一个循环,它取一个大列表中的前100项,与它们做一些事情,然后下一个100等,但当它接近结束时,它会自动缩短"100"步骤到剩余的项目.
目前我必须使用两个if循环:
for (int i = 0; i < listLength; i = i + 100)
{
if (i + 100 < listLength)
{
//Does its thing with a bigList.GetRange(i, 100)
}
else
{
//Does the same thing with bigList.GetRange(i, listLength - i)
}
}
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法呢?如果不是,我将至少使"事物"成为一个函数,因此代码不必被复制两次.
adr*_*dar 48
您可以使用LINQ Skip
,Take
并且您的代码将更清晰.
for (int i = 0; i < listLength; i=i+100)
{
var items = bigList.Skip(i).Take(100);
// Do something with 100 or remaining items
}
Run Code Online (Sandbox Code Playgroud)
注意:如果项目小于100,Take
则会给出剩余的项目.
Kyl*_*e W 13
我不喜欢列出的任何答案,所以我做了自己的扩展:
public static class IEnumerableExtensions
{
public static IEnumerable<IEnumerable<T>> MakeGroupsOf<T>(this IEnumerable<T> source, int count)
{
var grouping = new List<T>();
foreach (var item in source)
{
grouping.Add(item);
if(grouping.Count == count)
{
yield return grouping;
grouping = new List<T>();
}
}
if (grouping.Count != 0)
{
yield return grouping;
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以使用它:
foreach(var group in allItems.MakeGroupsOf(100))
{
// Do something
}
Run Code Online (Sandbox Code Playgroud)
pan*_*ene 11
在 dotnet 6 中你可以使用块:
//Child collections will be comprised of 10 elements each.
IEnumerable<int[]> sublists = numbers.Chunk(10);
Run Code Online (Sandbox Code Playgroud)
https://exceptionnotfound.net/bite-size-dotnet-6-chunk-in-linq/
还有一个参考使用 group by 来执行此操作,这对于旧版本的框架来说是一个非常有趣的解决方案: 使用 LINQ 将集合拆分为“n”部分?
您可以为终点保留一个显式变量:
for (int i = 0, j; i < listLength; i = j)
{
j = Math.min(listLength, i + 100);
// do your thing with bigList.GetRange(i, j)
}
Run Code Online (Sandbox Code Playgroud)