作为提醒,我目前正在学习C#,并在阅读一本教科书时遇到了这个障碍。
如何从IEnumerable<T>中调用 ElementAt? 此 SO 问题中的第二条评论提到了它,但我只得到了一个错误。 这里 他们也提到了这样做,但他们没有告诉你如何!
如果我遗漏了一些基本内容,请看看我的代码:
我从 MSDN Library page 获取的信息得出了这个结论:
所有这些都来自于关于集合的部分,第二段代码实现使得从列表中获取特定元素比必须遍历枚举器更加容易。
如何从IEnumerable<T>中调用 ElementAt? 此 SO 问题中的第二条评论提到了它,但我只得到了一个错误。 这里 他们也提到了这样做,但他们没有告诉你如何!
如果我遗漏了一些基本内容,请看看我的代码:
using System.Collections.Generic;
class Card {}
class Deck
{
public ICollection<Card> Cards { get; private set; }
public Card this[int index]
{
get { return Cards.ElementAt(index); }
}
}
我从 MSDN Library page 获取的信息得出了这个结论:
class Deck
{
public ICollection<Card> Cards { get; private set; }
public Card this[int index]
{
get {
return System.Linq.Enumerable.ElementAt<Card>(Cards, index);
}
}
}
所有这些都来自于关于集合的部分,第二段代码实现使得从列表中获取特定元素比必须遍历枚举器更加容易。
Deck deck = new Deck();
Card card = deck[0];
而不是:
Deck deck = new Deck();
Card c1 = null;
foreach (Card card in deck.Cards){
if (condition for the index)
c1 = card;
}
我是否做对了,或者我漏掉了什么?感谢任何意见!
Enumerator
。当然,当你调用ToList
或类似的方法时,实际上会迭代一次。 - King KingCards
实际上是一个IList
,ElementAt
将会使用它的索引器。 - p.s.w.g