Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get certain item from each Tuple from List

What is the correct way to go about creating a list of, say, the first item of each Tuple in a List of Tuples?

If I have a List<Tuple<string,string>>, how would I get a List<string> of the first string in each Tuple?

like image 620
Wilson Avatar asked Jan 15 '13 20:01

Wilson


People also ask

How do you extract values from a list of tuples?

To extract the n-th elements from a list of tuples with Python, we can use list comprehension. We get the n-th element from each tuple and put them into a list with [x[n] for x in elements] . x is the tuple being retrieved. Therefore, e is [1, 3, 5] .

How do you access elements in a list of tuples?

In the majority of programming languages when you need to access a nested data type (such as arrays, lists, or tuples), you append the brackets to get to the innermost item. The first bracket gives you the location of the tuple in your list. The second bracket gives you the location of the item in the tuple.


2 Answers

A little Linq will do the trick:

var myStringList = myTupleList.Select(t=>t.Item1).ToList();

As an explanation, since Tim posted pretty much the same answer, Select() creates a 1:1 "projection"; it takes each input element of the Enumerable, and for each of them it evaluates the lambda expression and returns the result as an element of a new Enumerable having the same number of elements. ToList() will then spin through the Enumerable produced by Select(), and add each element one at a time to a new List<T> instance.

Tim has a good point on the memory-efficiency; ToList() will create a list and add the elements one at a time, which will cause the List to keep resizing its underlying array, doubling it each time to ensure it has the proper capacity. For a big list, that could cause OutOfMemoryExceptions, and it will cause the CLR to allocate more memory than necessary to the List unless the number of elements happens to be a power of 2.

like image 134
KeithS Avatar answered Nov 04 '22 23:11

KeithS


List<string> list = tuples.Select(t => t.Item1).ToList();

or, potentially less memory expensive:

List<string> list = new List<String>(tuples.Count);
list.AddRange(tuples.Select(t => t.Item1));

because it avoids the doubling algorithm of List.Add in ToList.

like image 43
Tim Schmelter Avatar answered Nov 04 '22 21:11

Tim Schmelter