c# - ICollection<T> 上的 ElementAt(index)

标签 c# linq extension-methods indexer

请注意,我目前正在学习 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/

相关文章:

c# - OAuth 无法取消注释 OAuthWebSecurity.RegisterGoogleClient() 行

c# - LINQ 是一个有效的选项吗?

extension-methods - 扩展方法是访问者模式的一个例子吗?

c# - 我将如何为 System.Data.Linq.Table<T> 编写扩展方法?

php - 为 PHP 启用 zip 扩展

c# - Selenium Chrome 60 Headless 处理基于 HTTPS 的基本身份验证 SAML 对话框

c# - Unity3D - 将自定义 header 添加到 WWWForm

c# - 在linq语句中添加自定义函数

linq - 无法将类型 ‘System.Linq.IQueryable<AnonymousType#1>’ 隐式转换为 ‘System.Collections.Generic.IEnumerable<SubCateViewModel>’

c# - 在了解每个 Select/SelectMany 结果的同时转换 Linq 中的序列