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

3

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

当我使用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();
    }
}

}


2
你需要在 Reeks 中实现 IEnumerable<int> 和非泛型版本。 - Lee
1个回答

5
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();
    }
}

请注意,你的可枚举对象返回一个无限列表。 因此,当你枚举它时,需要手动终止它,使用类似于 Take()TakeWhile() 的方法。

使用 where 不会终止枚举,因为.NET框架不知道你的枚举器仅发出递增的值,因此它将一直枚举下去(或者直到你结束进程)。你可以尝试像这样的查询:

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

非常感谢,我真的很苦恼! - user3599415

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接