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

如何基于Choice枚举使用Linq返回IEnumerable<int>?

问题:用Linq根据枚举参数返回对应集合

我正在尝试用Linq解决这个问题,不知是否有人有思路?查找这类特定用例难度较大,希望该问题尚未被提出(可能只是我没找到)。

代码示例

public class Test
{
    public int a;
    public int b;
}

public Test[] testArray;

public enum Choice { A,B, Both = A|B }

public IEnumerable<int> GetEnumerable(Choice choice)
{
    //需要使用Linq方法根据choice返回可枚举集合
}

//示例:testArray = { (1,2), (3,4), (5,6) }
//调用GetEnumerable(Choice.A) → 返回1,3,5
//调用GetEnumerable(Choice.Both) → 返回1,2,3,4,5,6

补充说明

  • 大家都关注了问题的次要部分——确实缺少[Flags]特性,枚举项也应为2的幂才能用作标志。
  • 我已找到合适的解决方案:遍历集合,用yield return返回IEnumerable即可,这也是我之前的思路,只是之前没意识到可以直接用yield return,反而去实现了枚举器。
  • 其他基于Linq的方案大多过度依赖实例化新对象,虽然能快速实现,但不符合我的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 06:10:38