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

如何通过LINQ根据索引从列表中选取多个元素?

用LINQ根据指定索引提取数组元素的实现方法

已知你有如下数组(修正为C#标准写法):

var items = new object[] { new {}, new {}, new {}, new {}, new {}, new {} };

以及包含目标元素索引的列表:

List<int> myIndexes = new List<int> { 0, 3, 5 };

要实现类似var myNewItems = items.Something(myIndexes)的LINQ风格调用,有两种实用方式:

1. 自定义扩展方法(最贴合你的需求形式)

你可以编写一个LINQ风格的扩展方法,让数组直接调用该方法获取目标元素:

public static class EnumerableExtensions
{
    public static IEnumerable<T> GetItemsByIndexes<T>(this IEnumerable<T> source, IEnumerable<int> indexes)
    {
        // 参数合法性校验,避免空引用或无效索引
        if (source == null) throw new ArgumentNullException(nameof(source));
        if (indexes == null) throw new ArgumentNullException(nameof(indexes));
        
        var sourceList = source.ToList();
        foreach (var index in indexes)
        {
            if (index >= 0 && index < sourceList.Count)
                yield return sourceList[index];
        }
    }
}

之后就能像你期望的那样调用:

var myNewItems = items.GetItemsByIndexes(myIndexes);

2. 直接用现有LINQ方法组合实现

如果不想自定义扩展方法,也可以直接用LINQ原生方法组合完成:

var myNewItems = myIndexes.Where(i => i >= 0 && i < items.Length)
                          .Select(i => items[i]);

或者用查询表达式形式:

var myNewItems = from index in myIndexes
                 where index >= 0 && index < items.Length
                 select items[index];

注意:两种方式都建议加入索引合法性判断,避免触发索引越界异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 08:11:27