从索引在()中的列表中获取项

本文关键字:列表 获取 索引 | 更新日期: 2023-09-27 18:19:05

我有一个CustomClassItem的列表。我有几个整数,它们是我想要检索的项的索引。

最快/最有效的方法是什么?有一个以上索引的索引运算符或者myList.GetWhereIndexIs(myIntsList) ?

从索引在()中的列表中获取项

您可以使用Linq:

List<CustomClassItem> items = myIntsList.Select(i => myList[i]).ToList();

确保myIntsList.All(i => i >= 0 && i < myList.Count);

编辑:

如果列表中不存在索引,则忽略该索引:

List<CustomClassItem> items = myIntsList.Where(i => i >= 0 && i < myList.Count)
                                        .Select(i => myList[i]).ToList();

我认为一个很好的和有效的解决方案是将yield与扩展方法结合使用:

public static IList<T> SelectByIndex<T>(this IList<T> src, IEnumerable<int> indices)
{
    foreach (var index in indices) {
        yield return src[index];
    }
}

现在你可以输入:myList.SelectByIndex(new [] { 0, 1, 4 });

你也可以使用params对象:

public static IList<T> SelectByIndexParams<T>(this IList<T> src, params int[] indices)
{
    foreach (var index in indices) {
        yield return src[index];
    }
}

现在你可以输入:myList.SelectByIndexParams(0, 1, 4);

你想要的(如果我没看错的话)是:

var indices = [ 1, 5, 7, 9 ];
list.Where((obj, ind) => indices.Contains(ind)).ToList();

这将给你一个List<CustomClassItem>,其中包含所有索引在你的列表中的项目。

几乎所有的LINQ扩展方法都接受以T 为参数的函数,即T在Enumerable中的索引。

另一种使用Enumerable.Join:

的方法
var result = myList.Select((Item, Index) => new { Item, Index })
    .Join(indices, x => x.Index, index => index, (x, index) => x.Item);

更有效和安全(确保索引存在),但比其他方法可读性差。

也许你想创建一个增加可读性和可重用性的扩展:

public static IEnumerable<T> GetIndices<T>(this IEnumerable<T> inputSequence, IEnumerable<int> indices)
{
    var items = inputSequence.Select((Item, Index) => new { Item, Index })
       .Join(indices, x => x.Index, index => index, (x, index) => x.Item);
    foreach (T item in items)
        yield return item;
}

那么你可以这样使用它:

var indices = new[]{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
var first5 = myList.GetIndices(indices).Take(5);

使用Take来演示linq的延迟执行在这里仍然有效