2

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?

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
USS-Montana
  • 397
  • 4
  • 15
  • Possible duplicate of [How do you add an index field to Linq results](http://stackoverflow.com/questions/269058/how-do-you-add-an-index-field-to-linq-results) – qxg Sep 01 '16 at 07:38
  • 1
    You shouldn't edit questions to make existing answer invalid. You should instead add an update at the end of the existing question. – Enigmativity Sep 01 '16 at 07:39

3 Answers3

6

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)));
Graham
  • 7,431
  • 18
  • 59
  • 84
Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
1

Use Enumerable.Range to generate the numbers:

Enumerable.Range(0,number).Select(i=>new SomeEntity(someFunction(i)));
Damien_The_Unbeliever
  • 234,701
  • 27
  • 340
  • 448
0

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)));    
    }
}
Phillip Ngan
  • 15,482
  • 8
  • 63
  • 79