beta
beta

Reputation: 5666

Get array consisting of first values of a list of tuples

In my C# code I have a list of Tuples. The tuples themselves consist of two numbers of the type double and an object of type LocalDate.

List<Tuple<double, double, LocalDate>> tupleList = new List<Tuple<double, double, LocalDate>>();

The list, for instance, could look as follows.

1, 10, LocalDate1
12, 310, LocalDate2
31, 110, LocalDate3

What is an elegant way to create an array of doubles that only contains the first double values of each list item?

Accordingly, I want an ArrayList that only consists of the LocalDate objects in the list. The order should be preserved.

The expected result should be:

double[] => [1, 12, 31]
double[] => [10, 310, 110]
ArrayList<> => [LocalDate1, LocalDate2, LocalDate3]

I am aware that the ordinary way would be to iterate over the list in a for loop and create the arrays via this loop. However, I think that there should be a more concise and elegant way.

Upvotes: 2

Views: 1282

Answers (2)

Christopher
Christopher

Reputation: 9804

This can be done with a baseline for loop:

//Sorry for any Syntax errors. Got no VS installation in reach
double[] output = new double[tupleList.Length];

for(int i = 0; i < tupleList.Length; i++){
  output[i] = tupleList[i].Item1;
}

Of course something like linq or anything that uses lambdas in general might be more modern. But I doubt it is faster or more memory efficient. It has to use a List of some sort and create an array from that.

Upvotes: 1

pappbence96
pappbence96

Reputation: 1204

Linq would be the way to go:

var firstValues = tupleList.Select(x => x.Item1).ToList();

This projects the list of Tuples into a list of the first items only, keeping their order. Same with the second, third, n'th item as well.
If you want an array, just invoke ToArray() instead of ToList().

Upvotes: 7

Related Questions