Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use local variable in linq query in C#?

Tags:

c#

I have an array of integers say int[] vals.

I want to use linq query to get a list of points from this array of ints.

For example if i have array like this:

vals = new int[]{20,25,34}; 

I want my list of points as

var points = List<Point>{new Point(1,20),new Point(2,25),new Point(3,34)};

I want to use a local variable which is incremented by 1 for all int values in my array which will be the x value of my point.

How can I achieve this result using LINQ in C# ?

like image 400
Embedd_0913 Avatar asked Jan 19 '23 21:01

Embedd_0913


1 Answers

You could use the 2nd overload of Select:

var list = vals.Select((val, idx) => new Point(idx + 1, val)).ToList();

where idx is the index of val in vals.

like image 148
digEmAll Avatar answered Jan 21 '23 10:01

digEmAll