找不到源类型的查询模式的实现

Could not find an implementation of the query pattern for source type

我正在尝试打印并获取一行数字 (2,4,8,16, 32, ),但是使用 LINQ 表达式应该大于 10 但小于 1000。我不知道我做错了什么。

错误发生在我的program.cs中,当我使用 from 时,它在 r 下划线。我不明白这个错误是什么意思。

program.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

 namespace _3._4
 {
    class Program
{
    static void Main(string[] args)
    {
        Reeks r = new Reeks();

      var query =
                     from i in r// error is here
                     where i > 10 && i < 1000
                     select 2 * i;

        foreach (int j in query)
        {

            Console.Write(j);


        }
    }
}

}

Reeks.cs:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace _3._4
 {
    class Reeks : IEnumerable
{
    private int i = 1;
    public Reeks() {  }

    public IEnumerator GetEnumerator()
    {
        while (true)
        {
            i = i * 2;
            yield return i;
        }
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

}

Linq(即您正在使用的 from i in r 语法)要求您实现 IEnumerable<T> 接口,而不是 IEnumerable。因此,正如 Lee 指出的那样,您可以像这样实现 IEnumerable<int>

class Reeks : IEnumerable<int>
{
    private int i = 1;
    public Reeks() {  }

    public IEnumerator<int> GetEnumerator()
    {
        while (true)
        {
            i = i * 2;
            yield return i;
        }
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

请注意,您的可枚举 returns 是一个无限列表。因此,当您枚举它时,您需要使用 Take()TakeWhile().

之类的东西手动终止它

使用 where 不会终止枚举,因为 .NET 框架不知道您的枚举器只会发出递增的值,因此它将永远枚举(或直到您终止进程)。您可以改为尝试这样的查询:

var query = r.Where(i => i > 10)
                      .TakeWhile(i => i < 1000)
                      .Select(i => 2 * i);