【发布时间】:2013-11-16 00:36:43
【问题描述】:
提醒一下,我目前正在学习 C#,遇到这个障碍时正在阅读教科书。
如何从IEnumerable<T> 调用ElementAt?
this中的第二条评论
SO question提到它,但我只是得到一个错误。
Here 他们也提到了这样做,但他们没有告诉你如何!
如果我缺少一些基本的东西,这是我的代码:
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或者类似的方法时,你实际上是迭代了一次 -
我得到的错误是它找不到定义
-
@KingKing 当然,如果
Cards实际上是IList,ElementAt无论如何都会使用它的索引器。 -
@p.s.w.g 貌似OP的卡是icollection,如果也实现了IList就OK了。
标签: c# linq extension-methods indexer