Search code examples
c#listlinqlambdageneric-collections

C# List Lambda with index, object and DoStuff() / to array


Is there a way I can simplify this code?

double[] timeline = new double[dataList.Count];

for (int i = 0; i < dataList.Count; i++){
          timeline[i] = dataList[i].position;
}

return timeline;

First thought:

new double[datalist.ToArray("lambda which selects all .position attributes") <- is this possible?

Second thought:

datList.Select((x, i) => timeline[i] = x)

Something link that but this doesn't work... I googled a lot, couldn't find any solution.

I want to simplify that because I love lamda expressions and I wanna learn more about them.


Solution

  • Unless I'm missing something obvious here, why not simply use Select and ToArray?

    double[] timeline = dataList.Select(d => d.position).ToArray();