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

use*_*415 3 c# linq ienumerable

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

当我使用时,我的program.cs中出现错误,它强调了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);


        }
    }
}
Run Code Online (Sandbox Code Playgroud)

}

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

}

AJ *_*son 5

Linq(即from i in r您使用的语法)要求您实现IEnumerable<T>接口,而不是IEnumerable.所以,正如李指出的那样,你可以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();
    }
}
Run Code Online (Sandbox Code Playgroud)

作为注释,您的枚举返回无限列表.因此,当您枚举它时,您需要使用Take()或等手动终止它TakeWhile().

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

var query = r.Where(i => i > 10)
                      .TakeWhile(i => i < 1000)
                      .Select(i => 2 * i);
Run Code Online (Sandbox Code Playgroud)