You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在分页过滤时将IEnumerable符合索引条件的记录复制到目标集合?

解决分页过滤时收集符合条件记录到集合的问题

看起来你需要在分页过滤过程中,把当前页的符合条件记录同步收集到_invMstrSrchResults集合里对吧?这里有几个关键调整点,我来一步步帮你实现:

1. 调整集合类型,支持元素添加

首先要注意:IEnumerable<T>是只读接口,没办法直接添加元素。所以我们需要把_invMstrSrchResults改成可修改的集合类型(比如List<InventoryMasterItem>),并提前初始化:

// 替换原IEnumerable声明,改用List并初始化
private List<InventoryMasterItem> _invMstrSrchResults = new List<InventoryMasterItem>();
// 如果需要对外暴露只读的IEnumerable,可以加个属性
public IEnumerable<InventoryMasterItem> InvMstrSrchResults => _invMstrSrchResults;

2. 切换页码时清空旧结果

每次切换页码时,旧的分页记录需要被清空,避免新旧数据混淆。可以给CurrentPageIndex添加setter逻辑,在页码变更时自动清空集合并重新触发过滤:

private int _currentPageIndex;
public int CurrentPageIndex
{
    get => _currentPageIndex;
    set
    {
        _currentPageIndex = value;
        // 清空旧的分页结果
        _invMstrSrchResults.Clear();
        // 重新触发过滤逻辑
        ViewList.View.Refresh();
        CalculateTotalPages();
    }
}

3. 在Filter事件中收集符合条件的记录

现在可以在view_Filter的条件判断块里,把当前符合分页条件的记录添加到集合中:

void view_Filter(object sender, FilterEventArgs e)
{
    var currentItem = (InventoryMasterItem)e.Item;
    int index = currentItem.indexNo - 1;
    bool isInCurrentPage = index >= itemPerPage * CurrentPageIndex && index < itemPerPage * (CurrentPageIndex + 1);

    if (isInCurrentPage)
    {
        // 将符合条件的记录添加到目标集合
        _invMstrSrchResults.Add(currentItem);
    }

    e.Accepted = isInCurrentPage;
}

额外注意事项

  • 你原代码里的itemcount = 100;应该是笔误,建议改成itemPerPage = 100;,保证分页逻辑变量名统一
  • 如果数据源pvm是动态更新的,记得在数据源变更时也清空_invMstrSrchResults并重新触发过滤

完整调整后的代码参考

public PagingViewModel(IEnumerable<InventoryMasterItem> pvm)
{
    ViewList = new CollectionViewSource();
    ViewList.Source = pvm;
    ViewList.Filter += view_Filter;
    CurrentPageIndex = 0;
    itemPerPage = 100; // 修正变量名,确保分页条数正确
    CalculateTotalPages();
}

private int _currentPageIndex;
public int CurrentPageIndex
{
    get => _currentPageIndex;
    set
    {
        _currentPageIndex = value;
        _invMstrSrchResults.Clear();
        ViewList.View.Refresh();
        CalculateTotalPages();
    }
}

private int itemPerPage;
private List<InventoryMasterItem> _invMstrSrchResults = new List<InventoryMasterItem>();
public IEnumerable<InventoryMasterItem> InvMstrSrchResults => _invMstrSrchResults;

void view_Filter(object sender, FilterEventArgs e)
{
    var currentItem = (InventoryMasterItem)e.Item;
    int index = currentItem.indexNo - 1;
    bool isInCurrentPage = index >= itemPerPage * CurrentPageIndex && index < itemPerPage * (CurrentPageIndex + 1);

    if (isInCurrentPage)
    {
        _invMstrSrchResults.Add(currentItem);
    }

    e.Accepted = isInCurrentPage;
}

内容的提问来源于stack exchange,提问作者user3422209

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:20:04