【问题标题】:How to page an array using LINQ?如何使用 LINQ 对数组进行分页?
【发布时间】:2013-06-09 15:58:37
【问题描述】:

如果我有这样的数组:

string[] mobile_numbers = plst.Where(r => !string.IsNullOrEmpty(r.Mobile))
                                          .Select(r => r.Mobile.ToString())
                                          .ToArray();

我想分页这个数组并根据这些页面循环。

假设数组计数是400,我想取the first 20,然后是the second 20,依此类推,直到数组结束处理每个20 项目。

如何用 linq 做到这一点? .

【问题讨论】:

标签: c# arrays linq pagination


【解决方案1】:

使用SkipTake 方法进行分页(但请记住,它会为您要获取的每个页面迭代集合):

int pageSize = 20;
int pageNumber = 2;
var result = mobile_numbers.Skip(pageNumber * pageSize).Take(pageSize);

如果您只需要在“页面”上拆分数组,请考虑使用MoreLinq(可从 NuGet 获得)批处理方法:

var pages = mobile_numbers.Batch(pageSize);

如果您不想使用整个库,请查看Batch method implementation。或者使用这个扩展方法:

public static IEnumerable<IEnumerable<T>> Batch<T>(
     this IEnumerable<T> source, int size)
{
    T[] bucket = null;
    var count = 0;

    foreach (var item in source)
    {
        if (bucket == null)            
            bucket = new T[size];


        bucket[count++] = item;

        if (count != size)            
            continue;            

        yield return bucket;

        bucket = null;
        count = 0;
    }

    if (bucket != null && count > 0)
        yield return bucket.Take(count).ToArray();
}

用法:

int pageSize = 20;
foreach(var page in mobile_numbers.Batch(pageSize))
{   
    foreach(var item in page)
       // use items
}

【讨论】:

  • 如何获取页码?我在循环中使用这个方法对吗?
  • @just_name 你应该为你想要的页面提供页码。如果您需要在存储桶上拆分数组,请考虑使用 MoreLinq Batch 方法
  • 如何得出页码,你是不是除以400/20得到循环的限制??
  • for(int i =0 i&lt;20;i++) { }
  • @just_name 与你做的批次foreach(var page in pages)
【解决方案2】:

您需要一个批处理操作员。

There is one in MoreLinq that you can use.

你会像这样使用它(例如):

foreach (var batch in mobile_numbers.Batch(20))
    process(batch);

上述循环中的batch 将是一个最多包含 20 个项目的 IEnumerable(最后一批可能小于 20;所有其他的长度均为 20)。

【讨论】:

    【解决方案3】:

    您可以使用.Skip(n).Take(x); 跳转到当前索引并取所需数量。

    Take 只会在可用的数量少于请求的数量时获取可用的数量,即剩余的数量。

    【讨论】:

      猜你喜欢
      • 2014-01-06
      • 1970-01-01
      • 2011-01-23
      • 2015-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-05
      • 2020-01-18
      相关资源
      最近更新 更多