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

G. *_*bol 3 c# indexing list

我有一份清单CustomClassItem.我有几个int是我想要检索的项目的索引.

获得它们的最快捷/最有效的方法是什么?索引运算符的精神,有多个索引或者可能myList.GetWhereIndexIs(myIntsList)

Ahm*_*IEM 7

你可以使用Linq:

List<CustomClassItem> items = myIntsList.Select(i => myList[i]).ToList();
Run Code Online (Sandbox Code Playgroud)

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

编辑:

如果列表中不存在索引,请忽略此索引:

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


Eri*_*oom 5

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

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

现在你可以这样做: 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];
    }
}
Run Code Online (Sandbox Code Playgroud)

现在你可以这样做: myList.SelectByIndexParams(0, 1, 4);