【发布时间】:2018-11-02 14:39:46
【问题描述】:
我有IEnumerable 列表customerList 和索引。现在我想根据索引获取IEnumerable的项目。
例如,如果index = 3,它应该为我提供 IEnumerable 的第 3 项。
请指导。
IEnumerable<Customer> customerList = new Customer[]
{
new Customer { Name = "test1", Id = 999 },
new Customer { Name = "test2", Id = 915 },
new Customer { Name = "test8", Id = 986 },
new Customer { Name = "test9", Id = 988 },
new Customer { Name = "test4", Id = 997 },
new Customer { Name = "test5", Id = 920 },
};
int currentIndex = 3; //want to get object Name = "test8", Id = 986
【问题讨论】:
-
不要在这里使用
IEnumerable<T>。使用IList<T> -
你必须做
customerList.ToList()[2];。请记住,索引从 0 开始,而不是 1。 -
@Icemanind:
customerList.ToList()可能会在我们只需要 2-nd 时创建一个 enourmous 列表(甚至抛出OutOfMemory异常)项目 -
@Icemanind 当数组已经是 IList
时,没有理由使用 ToList()。只需将其转换为正确的类型。更好的是,不要首先使用IEnumerable<T> -
我不明白"How to get the index of an element in an IEnumerable" 是如何与"How to get the item from an IEnumerable using its index" 重复的。这是两件不同的事情,答案也不相关。
标签: c# ienumerable