我希望能够将 Linq 的“.where”语句与实现接口 IEnumerable 的“Books”类(“Book”列表)一起使用。
//THE PROBLEM IS HERE.
IEnumerable list3 = bookList.Where(n => n.author.Length >= 14);
我收到以下错误:
错误 1“Assignment2CuttingPhilip.Books”不包含“Where”的定义,并且找不到接受“Assignment2CuttingPhilip.Books”类型的第一个参数的扩展方法“Where”(是否缺少 using 指令或程序集引用?) C:\Users\Alex\Dropbox\cos570 CSharp\Assignment2CuttingPhilip\Assignment2CuttingPhilip\Assignment2PhilipCutting.cs 132 33Assignment2CuttingPhilip
我的代码如下:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Assignment2CuttingPhilip
{
public class Book
{
public string title;
public string author;
public Book(string title, string author) {
this.title = title;
this.author = author;
}
public override string ToString()
{ return "Title:\'" + title + "\', Author:" + author; }
}
public class Books : IEnumerable
{
private Book[] _books;
public Books(Book[] bArray){
_books = new Book[bArray.Length];
for (int i = 0; i < bArray.Length; i++)
{_books[i] = bArray[i];}
}
IEnumerator IEnumerable.GetEnumerator()
{return (IEnumerator) GetEnumerator();}
public BooksEnum GetEnumerator()
{return new BooksEnum(_books);}
}
public class BooksEnum : IEnumerator{
public Book[] _books;
int position = -1;
public BooksEnum(Book[] list){
_books = list;}
public bool MoveNext()
{
position++;
return (position < _books.Length);
}
public void Reset()
{position = -1;}
object IEnumerator.Current
{ get { return Current; }}
public Book Current
{{ try
{ return _books[position];}
catch (IndexOutOfRangeException)
{throw new InvalidOperationException();}
}}
}
class Assignement2PhilipCutting
{
static void Main(string[] args)
{
Book[] bookArray = new Book[3]
{
new Book("Advance C# super stars", "Prof Suad Alagic"),
new Book("Finding the right lint", "Philip Cutting"),
new Book("Cat in the hat", "Dr Sues")
};
Books bookList = new Books(bookArray);
IEnumerable List = from Book abook in bookList
where abook.author.Length <= 14
select abook;
IEnumerable list2 = bookArray.Where(n => n.author.Length >= 14);
//**THE PROBLEM IS HERE**.
IEnumerable list3 = bookList.Where(n => n.author.Length >= 14);
foreach (Book abook in List)
{ Console.WriteLine(abook); }
}
}
}
这样做应该非常简单,但为什么我不能在 C# 中将我的可枚举图书列表与 Linq 一起使用?难道我不应该能够创建一个可以使用 Fluent Linq 命令查询的可枚举列表吗?
谢谢
菲尔
Your Books
类必须实现IEnumerable<Book>
, 不只是IEnumerable
. The Where
与大多数 LINQ 扩展一样,扩展是为实现IEnumerable<T> http://msdn.microsoft.com/en-us/library/9eekhta0%28v=vs.110%29.aspx。该接口位于System.Collections.Generic
命名空间。
现在你可以使用Cast() http://msdn.microsoft.com/en-us/library/bb341406%28v=vs.110%29.aspx扩大:
var list3 = bookList.Cast<Book>().Where(n => n.author.Length >= 14);
这是您可以对仅实现的遗留集合执行的操作IEnumerable
。但是,在您的场景中,Books
类是你的,所以我真的建议你实现它IEnumerable<Book>
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)