Zed
Zed

Reputation: 671

Getting individual values from an element in a List

I currently have this and it works absolutely fine, just getting the values I don't understand.

List<Tuple<int,int>> snake = new List<Tuple<int, int>>();
...
snake.Insert(0, Tuple.Create(x, y));
...
Console.Writeline(snake[5]);

Output ex: (5, 198)

-

How would I just get the x or the y value, such

Console.Writeline(snake[5][0]);

Would output 5

For example

Edit:

Nevermind found the answer

int sx = snake[Blength-1].Item1;

Upvotes: 0

Views: 86

Answers (3)

eddie_cat
eddie_cat

Reputation: 2583

You can use Tuple.Item1, Tuple.Item2, etc. See the example here:

http://msdn.microsoft.com/en-us/library/dd384265(v=vs.110).aspx

var tuple1 = Tuple.Create(12);
Console.WriteLine(tuple1.Item1);     // Displays 12

Upvotes: 0

Zed
Zed

Reputation: 671

You can select which item you want by adding .Item#

snake[5].Item1;

Upvotes: 1

Erik Schierboom
Erik Schierboom

Reputation: 16636

A tuple cannot be accessed through an indexer. You can do this:

Console.WriteLine(snake[5].Item1); // Will output 5

If you want to access the second item, do this:

Console.WriteLine(snake[5].Item2); // Will output 198

Note: the maximum number of items that you can place in a single tuple is 8 by the way (source).

Upvotes: 1

Related Questions