2

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.

Abhilash Ravindran C K
  • 1,818
  • 2
  • 13
  • 22

2 Answers2

4

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

double[] timeline = dataList.Select(d => d.position).ToArray();
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
Zohar Peled
  • 79,642
  • 10
  • 69
  • 121
  • @TimSchmelter why not use `var` here? – Zohar Peled Mar 13 '18 at 09:54
  • Because the question is about how to create a `double[]` with LINQ and because the type is not obvious. I just wanted to clarify that OP gets what he has asked for, `var` obfuscates this. – Tim Schmelter Mar 13 '18 at 09:56
  • i tested that but tried double[] timeline = new double[dataList.Select(d => d.position).ToArray()]; and that got me an error cause it expected an int... i failed understanding the error message, thanks this work ! @TimSchmelter is there also a way to "do stuff" in the select lambda ? since its the only one you can get the index AND the object from – felixbreuer Mar 13 '18 at 10:20
  • @ScriptWorld write a function and call it in the select: `items.Select((d,index) => SomeInportantFunction(d.position,index))` – Chrᴉz remembers Monica Mar 13 '18 at 10:27
  • @ScriptWorld: well, a LINQ query is not supposed to "do stuff". It's supposed to query some stuff. Don't let it cause side-effects. You would trigger them whenever you "touch" this query(f.e. calling `ToList` or enumerate it in a foreach). Instead query everything what you want to "do stuff" with. Then use a plain `foreach`-loop to actually do it. – Tim Schmelter Mar 13 '18 at 10:32
  • @Chriz thanks ! thats a simple way, didnt know thats possible. – felixbreuer Mar 13 '18 at 11:09
  • @Tim Schmelter thats reasoned... i guess ill just stick to those foreach loops in these cases. – felixbreuer Mar 13 '18 at 11:11
2

You can simply use projection (i.e. Select LINQ method):

IEnumerable<double> timeLine = dataList.Select(dl => dl.position);

If you need to convert it to array, you can just use ToArray method

Darjan Bogdan
  • 3,780
  • 1
  • 22
  • 31