【问题标题】:Why can't I use LINQ methods on my class implementing IEnumerable?为什么我不能在实现 IEnumerable 的类上使用 LINQ 方法?
【发布时间】:2012-01-17 10:54:01
【问题描述】:

我必须完成一个项目,但我有一个简单的问题

我有一个这样定义的类

using System;
using System.Collections;
using System.Collections.Generic;

..

public class GroupId: XmlDataTransferObject, IEnumerable
{
    private IList _groupId;
    private string _nameId;

    public GroupId() : this("GroupId", "Id")
    {
    }

    public GroupId(string rootName, string nomeId) : base(rootName)
    {
        _groupId = new ArrayList();
        _nomeId = nomeId;
    }

    public override bool IsNull
    {
        get { return _groupId.Count == 0; }
    }

    public int Count
    {
        get { return _groupId.Count; }
    }

    public int Add(Intero i)
    {
        return _groupId.Add(i);
    }

    public Intero this[int index]
    {
        get { return (Intero)_groupId[index]; }
        set { _groupId[index] = value; }
    }
...

            public IEnumerator GetEnumerator()
            {
                    return _groupId.GetEnumerator();
            }
}

}

我需要找到两个 GroupId 对象的实例之间的交集。

即使我声明了语句,为什么我在可用方法中看不到 Linq Intersect:

Using System.Linq 

...

var x = _groupId1.Intersect(_groupId2);

...

错误 1 ​​'....GroupId' 不包含 'Intersect' 的定义,并且找不到接受类型为 '...GroupId' 的第一个参数的扩展方法 'Intersect'(您是否缺少 using 指令还是程序集参考?)

【问题讨论】:

  • 我假设Using System.Linqusing System.Linq; 的拼写错误(小写using 和末尾的分号)

标签: c# linq extension-methods intersect


【解决方案1】:

您的 GroupId 类仅实现非泛型 IEnumerable 类 - 如果您想使用 LINQ 扩展方法,您应该实现 IEnumerable<T>。 (无论如何,这通常会是更好的体验。)

请注意,如果您使用泛型 IList<T> 而不是非泛型 IList,这也会更容易 - 如果可能的话,基本上尽量避免在新代码中完全使用非泛型集合。

可以使用Cast 将您的IEnumerable 转换为IEnumerable<T>,如下所示:

var x = _groupId1.Cast<Intero>().Intersect(_groupId2.Cast<Intero>());

...但是让你的类实现IEnumerable&lt;Intero&gt;会更好。

【讨论】:

    【解决方案2】:

    因为您的_groupId1 被声明为IList,而这只是IEnumerable

    对于几乎所有 linq 扩展方法,您都需要一个通用的可枚举 (IEnumerable&lt;T&gt;)。您的选择是更改声明,或使用Cast&lt;T&gt;OfType&lt;T&gt; 扩展之一。

    试试_groupId1.OfType&lt;Intero&gt;().Intersect(...)

    或将其声明为IList&lt;Intero&gt;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-13
      • 1970-01-01
      • 2022-10-04
      • 2014-04-02
      • 2010-11-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多