作者:萌萌美人鱼 | 来源:互联网 | 2022-11-30 18:14
我有IEnumerable
列表customerList
和索引.现在我想得到IEnumerable
基于索引的项目.
例如,如果index = 3
,它应该提供IEnumerable的第3项.
请指导.
IEnumerable 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
Tim Schmelte..
8
例如,如果index = 3,它应该为我提供IEnumerable的第3项
你知道.NET中的索引是零吗?但是,您可以使用ElementAt
:
Customer c = customerList.ElementAt(currentIndex); // 4th
使用ElementAtOrDefault
以防止如果没有足够的项目一个例外,那么你会得到null
:
Customer c = customerList.ElementAtOrDefault(currentIndex); // 4th or null
这些方法以使用IList
索引器的方式进行优化.所以在你的例子中实际上有一个Customer[]
实现该接口,因此它将使用索引器.
如果序列未实现IList
,则将枚举它以在此索引处查找项目.
1> Tim Schmelte..:
例如,如果index = 3,它应该为我提供IEnumerable的第3项
你知道.NET中的索引是零吗?但是,您可以使用ElementAt
:
Customer c = customerList.ElementAt(currentIndex); // 4th
使用ElementAtOrDefault
以防止如果没有足够的项目一个例外,那么你会得到null
:
Customer c = customerList.ElementAtOrDefault(currentIndex); // 4th or null
这些方法以使用IList
索引器的方式进行优化.所以在你的例子中实际上有一个Customer[]
实现该接口,因此它将使用索引器.
如果序列未实现IList
,则将枚举它以在此索引处查找项目.