user3599415
user3599415

Reputation: 283

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

I am trying to print and get a row of numbers(2,4,8,16, 32, ) but then is should be greater than 10 but smaller than 1000 with LINQ expressions. I don't know what i am doing wrong.

The error occurs in my program.cs when i use from, it underlines r. I don't understand what this error means.

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

}

Upvotes: 3

Views: 2404

Answers (1)

AJ Richardson
AJ Richardson

Reputation: 6820

Linq (i.e. the from i in r syntax you are using) requires you to implement the IEnumerable<T> interface, not IEnumerable. So, as Lee pointed out, you can just implement IEnumerable<int> like this:

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

As a note, your enumerable returns an infinite list. As such, when you enumerate it, you need to terminate it manually using something like Take() or TakeWhile().

Using where will NOT terminate the enumeration, since the .NET framework does not know that your enumerator only emits increasing values, so it will keep enumerating forever (or until you kill the process). You might try a query like this instead:

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

Upvotes: 5

Related Questions