Could not find implementation of request pattern for source type

I'm trying to print and get a string of numbers (2,4,8,16,32,), but then it has to be greater than 10 but less than 1000 with LINQ expressions. I don't know what I am doing wrong.

The error occurring in my program.cs program when I use it it underscores 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();
    }
}

      

}

+3


source to share


1 answer


Linq (i.e. the syntax from i in r

you are using) requires an interface implementation IEnumerable<T>

, not IEnumerable

. So, as Lee pointed out, you can simply 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 side note, your enum returns an infinite list. So when you list it, you have to finish it manually using something like Take()

or TakeWhile()

.



Using where

does NOT complete the enumeration as the .NET framework doesn't know that your counter is only emitting increasing values, so it will enumerate continuously (or until you kill that process). You can try a query like this instead:

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

      

+4


source







All Articles