【问题标题】:Could not find an implementation of the query pattern for source type找不到源类型的查询模式的实现
【发布时间】:2015-05-16 14:34:50
【问题描述】:

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

当我使用 from 时,我的 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);


        }
    }
}

}

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

}

【问题讨论】:

  • 你需要在Reeks以及非泛型版本中实现IEnumerable&lt;int&gt;

标签: c# linq ienumerable


【解决方案1】:

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

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);

【讨论】:

  • 非常感谢,我真的很挣扎!
猜你喜欢
  • 2015-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-10
  • 1970-01-01
  • 2012-01-03
相关资源
最近更新 更多