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

如何在Azure.ResourceManager中筛选/移除VirtualMachineResource(查询时或结果后)

解决方案:包装筛选后的结果为AsyncPageable

由于Azure.ResourceManager的VirtualMachineCollection无法直接修改,且GetAllAsync()暂时不支持基于Graph查询返回的VM ID列表进行服务端筛选,我们可以通过**客户端异步筛选并包装为新的AsyncPageable<VirtualMachineResource>**来满足需求,这样后续函数仍能接收标准的AsyncPageable类型,无需手动遍历冗余数据。

实现代码

public static AsyncPageable<VirtualMachineResource> GetVmList(ResourceGroupResource resourceGroup, FilterBy filterBy, List<string> filterList)
{
    // 将filterList转为HashSet提升查找性能(如果列表较大)
    var filterSet = new HashSet<string>(filterList, StringComparer.OrdinalIgnoreCase);

    return AsyncPageable.Create(async cancellationToken =>
    {
        // 获取原始的异步分页VM列表
        var originalVms = resourceGroup.GetVirtualMachines().GetAllAsync(cancellationToken);
        
        // 异步遍历并筛选
        await foreach (var vm in originalVms.WithCancellation(cancellationToken))
        {
            // 匹配VM的资源ID(根据实际场景调整匹配逻辑,比如仅匹配VM名称)
            if (filterSet.Contains(vm.Id.ToString()))
            {
                yield return vm;
            }
        }
    });
}

关键说明

  • 性能优化:将List<string>转为HashSet<string>,把查找时间复杂度从O(n)降到O(1),适合filterList较大的场景。
  • 匹配逻辑调整:如果filterList中存储的是VM名称而非完整资源ID,只需把vm.Id.ToString()替换为vm.Name即可。
  • 保留异步特性:通过AsyncPageable.Create包装筛选逻辑,完全保留原有的异步分页能力,不会一次性加载所有VM到内存。
  • 兼容性:返回的AsyncPageable<VirtualMachineResource>可以直接传递给其他依赖此类型的函数,无需修改原有调用逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 17:15:41