USS-Montana
USS-Montana

Reputation: 417

Yield return from an indexed iteration via LINQ

Leaving the performance cost of LINQ usage, I would like to know how to convert the following code into a LINQ expression

for (int i = 0; i < someArray.length(); i++)
  yield return new SomeEntity(someFunction(i));

Important: I need the use of the incremented index


Update:

Rather than someArray.length(), number should be used:

for (int i = 0; i < number; i++)
  yield return new SomeEntity(someFunction(i));

2nd update

I'm still getting the compilation error "not all code paths return value"

My code:

public static IEnumerable function()
{
    Enumerable.Range(0,5).Select(i => new Entity());
}

3rd update


Didn't think it's relevant until I found out it's the cause for this error..

public static IEnumerable function()
{
    int[] arr = { 1, 2, 3, 4 };
    foreach (int i in arr)
    {
        Enumerable.Range(0,5).Select(i => new Entity());
    }
}

If you take out the foreach 1st loop out of the equation, all replies answer to this question, but my issue is n^2.. 2 nested loops...

Any ideas?

Upvotes: 2

Views: 549

Answers (3)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149598

Use the overload of Enumerable.Select that has an index into the collection:

someArray.Select((x, i) => new SomeEntity(someFunction(i)));

Edit

As you've modified your example and are not actually using a collection to iterate and index to, use Enumerable.Range:

Enumerable.Range(0, number).Select(i => new SomeEntity(someFunction(i)));

Upvotes: 6

Phillip Ngan
Phillip Ngan

Reputation: 16126

Here's my LinqPad snippet.

void Main()
{

    var e = SomeEntity.GetEntities(new List<int> { 1, 2, 3});
    e.Dump();
}

public class SomeEntity
{
    public int m_i;
    public SomeEntity(int i)
    {
        m_i = i;
    }

    public override string ToString()
    {
        return m_i.ToString();
    }


    public static int someFunction(int i){ return i+100;}

    public static IEnumerable<SomeEntity> GetEntities(IEnumerable<int> someArray)
    {
//        for (int i = 0; i < someArray.Count();i++)
//            yield return new SomeEntity(someFunction(i));

        // *** Equivalent linq function ***    
        return someArray.Select(a => new SomeEntity(someFunction(a)));    
    }
}

Upvotes: 0

Damien_The_Unbeliever
Damien_The_Unbeliever

Reputation: 239764

Use Enumerable.Range to generate the numbers:

Enumerable.Range(0,number).Select(i=>new SomeEntity(someFunction(i)));

Upvotes: 1

Related Questions