C# 为什么可以';我不能在实现IEnumerable的类上使用LINQ方法吗?
我必须完成一个项目,但我有一个简单的问题 我有一个这样定义的类C# 为什么可以';我不能在实现IEnumerable的类上使用LINQ方法吗?,c#,linq,extension-methods,intersect,C#,Linq,Extension Methods,Intersect,我必须完成一个项目,但我有一个简单的问题 我有一个这样定义的类 using System; using System.Collections; using System.Collections.Generic; .. public class GroupId: XmlDataTransferObject, IEnumerable { private IList _groupId; private string _nameId; public GroupId() :
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相交:
Using System.Linq
...
var x = _groupId1.Intersect(_groupId2);
...
错误1“…GroupId”不包含“Intersect”的定义,并且找不到接受“…GroupId”类型的第一个参数的扩展方法“Intersect”(是否缺少using指令或程序集引用?)
您的
GroupId
类仅实现非泛型IEnumerable
类-如果要使用LINQ扩展方法,您应该实现IEnumerable
。(无论如何,这通常是一种更好的体验。)
请注意,如果您使用泛型的IList
而不是非泛型的IList
,那么这也会变得更容易-如果可能的话,基本上尽量在新代码中完全避免非泛型集合
您可以使用Cast
将IEnumerable
转换为IEnumerable
,如下所示:
var x = _groupId1.Cast<Intero>().Intersect(_groupId2.Cast<Intero>());
var x=\u groupId1.Cast().Intersect(\u groupId2.Cast());
。。。但是让类实现
IEnumerable
会更好,因为\u groupId1
被声明为IList
,它只是IEnumerable
几乎所有linq扩展方法都需要一个通用的可枚举(IEnumerable
)。您可以选择更改声明,或者使用类型扩展名的Cast
或
请尝试\u groupId1.OfType().Intersect(…)
或者将其声明为IList
我假设使用System.Linq
是使用System.Linq的打字错误
(小写,结尾使用
和分号)