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

I have an array of integers int[] vals .

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

For example, if I have an array as follows:

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

I need my list of points

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

I want to use a local variable that 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 with LINQ in C #?

+4
source share
4 answers

You can use the second overload Select :

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

where idx is the index of val in vals .

+9
source
 var vals = new int[]{20,25,34}; var x = 1; var points = vals.Select((val) => new Point(x++,val)).ToList(); 
0
source

Or the third option - get the ordinal list and project using this and the original array.

 var points = Enumerable.Range(1, vals.Count()) .Select(i => new Point(i, vals[i - 1])).ToList(); 
0
source
  var vals = new int[] { 20, 25, 34 }; int i = 0; var points = vals.ToList().ConvertAll(delegate(int v) { return new Point(++i, v); }); 
0
source

Source: https://habr.com/ru/post/1369473/


All Articles