请注意,我目前正在学习 C# 并在遇到这个障碍时翻阅教科书。
你怎么称呼ElementAt
来自 IEnumerable<T>
?
this中的第二条评论
所以问题提到了它,但我只是收到一个错误。
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;
}
我这样做是对的还是我遗漏了什么?感谢您的任何输入!
最佳答案
如果你想使用 Linq extension methods ,请确保在文件顶部包含 System.Linq
命名空间:
using System.Collections.Generic;
using System.Linq; // This line is required to use Linq extension methods
class Card {}
class Deck
{
public ICollection<Card> Cards { get; private set; }
public Card this[int index]
{
get { return Cards.ElementAt(index); }
}
}
当然,扩展方法只是带有一点语法糖的常规旧方法。您也可以这样调用它们:
using System.Collections.Generic;
class Card {}
class Deck
{
public ICollection<Card> Cards { get; private set; }
public Card this[int index]
{
get { return System.Linq.Enumerable.ElementAt(Cards, index); }
}
}
关于c# - ICollection<T> 上的 ElementAt(index),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20013115/