4

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# ?

4 Answers 4

9

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.

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

@Downvoter, could you comment? The OP asked for using a local variable in the query, which is what I do...
0

Or a third option - get an ordinal enumeration and project using that and your original array.

var points = Enumerable.Range(1, vals.Count())
    .Select(i => new Point(i, vals[i - 1])).ToList();

Comments

0
        var vals = new int[] { 20, 25, 34 };
        int i = 0;
        var points = vals.ToList().ConvertAll(delegate(int v) { return new Point(++i, v); });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.