0

Suppose I have this data int[] a = [1,2,3,4,5]

I would like to create Tuple<int,int,bool>[] where the first element is itself, the second is it's double value and the last element is whether it is an even number or not.

That is, the resulting data would be :

(1, 2, false)
(2, 4, true)
(3, 6, false)
(4, 8, true)
(5, 10, false)

One solution I have is to create a list, make a for loop over a array and new each Tuple, add to the list, and then finally use .ToArray on the list. But I think there must be an elegant way to do this. I don't mind using LINQ.

    int[] a = [1, 2, 3, 4, 5];
    List<Tuple<int,int,bool>> list = new List<Tuple<int, int, bool>>();
    {
        foreach(int i in a)
        {
            list.Add(new Tuple<int, int, bool>(i, i * 2, i % 2 == 0));
        }
    }
    return list.ToArray();
1

2 Answers 2

4

A simple Select should do the trick:

var tuples  = a.Select(v => Tuple.Create(v, v * 2, v % 2 == 0)).ToArray();
Sign up to request clarification or add additional context in comments.

Comments

1

Using a select query would solve the problem.

int[] a = [1, 2, 3, 4, 5];
var result =  a.Select(x => Tuple.Create<int, int, bool>(x, 2 * x, x % 2 == 0)).ToArray();

2 Comments

oh .. he got it first :(
@CamiloTerevinto in my answer it's v, not x, and also v * 2 and not 2 * x. Don't be too hard on the guy, sometimes you don't get the updates in time...

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.