1

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.

0

2 Answers 2

6

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().

5
  • Thanks. How can I get an ArrayList? Due to other code dependencies, I need exactly this typ.e
    – beta
    Jul 31, 2019 at 13:29
  • If you absolutely have to use ArrayList, there is a constructor with the signature ArrayList(ICollection). So you can use it like: ArrayList firstValues = new ArrayList(tupleList.Select(x => x.Item1).ToList()); Jul 31, 2019 at 13:32
  • Hm, that's strange. You could try passing the constructor argument as a named parameter: new ArrayList(c: tupleList.Select(x => x.Item1).ToList());, maybe this will force the compiler to use that specific constructor. Jul 31, 2019 at 13:39
  • sorry, my bad (that's why I deleted my comment): I am working with ikvm (java to C# code migration) and the ArrayList class was actually the java.util.ArrayList, hence the confusion. Thanks for your help.
    – beta
    Jul 31, 2019 at 13:42
  • You're welcome! If this answer helped you please consider marking it as accepted with the checkmark. Jul 31, 2019 at 13:53
1

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.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.