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

如何使用LINQ Where筛选包含指定RelatedId的ArrayList数据?

LINQ筛选包含指定ID的Apps实例解决方案

由于RelatedId是ArrayList非泛型集合,直接使用LINQ的Contains方法会存在类型匹配问题,需要先将其转换为强类型集合再进行判断。以下是具体实现代码:

1. 定义Apps类与示例数据

public class Apps
{
    public bool Active { get; set; }
    public ArrayList RelatedId { get; set; }
    public string Description { get; set; }
}

// 示例数据
var appsList = new List<Apps>
{
    new Apps { Active = true, RelatedId = new ArrayList {5, 6}, Description = "App1" },
    new Apps { Active = true, RelatedId = new ArrayList {3, 5}, Description = "App2" },
    new Apps { Active = true, RelatedId = new ArrayList {7, 8}, Description = "App3" },
    new Apps { Active = false, RelatedId = new ArrayList {5}, Description = "App4" }
};

2. LINQ筛选写法

方法链形式

int targetId = 5;
var filteredApps = appsList
    .Where(app => app.Active && app.RelatedId.OfType<int>().Contains(targetId))
    .ToList();

查询表达式形式

int targetId = 5;
var filteredApps = (from app in appsList
                    where app.Active && app.RelatedId.OfType<int>().Contains(targetId)
                    select app).ToList();

关键说明

  • OfType<int>():将ArrayList中的元素转换为int类型(需根据实际存储的数值类型调整,如long则改为OfType<long>()),同时过滤掉非目标类型的元素,避免类型转换异常。
  • 若能确保RelatedId中所有元素都是目标类型,也可使用Cast<int>()替代OfType<int>(),但Cast遇到非目标类型元素时会直接抛出异常,需谨慎使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 03:10:16