Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get specific item from list of tuples c#

Tags:

c#

list

tuples

I have a list of tuples:

List<Tuple<int, string, int>> people = new List<Tuple<int, string, int>>(); 

Using a dataReader, I may populate this list with various values:

people.Add(new Tuple<int, string, int>(myReader.GetInt32(4), myReader.GetString(3), myReader.GetInt32(5))); 

But then how do I loop through, getting each individual value. For example I may want to read the 3 details for a specific person. Lets say there is an ID, a name and a phone number. I want something like the following:

        for (int i = 0; i < people.Count; i++)         {             Console.WriteLine(people.Item1[i]); //the int             Console.WriteLine(people.Item2[i]); //the string             Console.WriteLine(people.Item3[i]); //the int                } 
like image 570
Wayneio Avatar asked Jul 23 '13 15:07

Wayneio


2 Answers

people is a list, so you index into the list first, and then you can reference whatever item you want.

for (int i = 0; i < people.Count; i++) {     people[i].Item1;     // Etc. } 

Just keep in mind the types that you're working with, and these kinds of mistakes will be few and far between.

people;          // Type: List<T> where T is Tuple<int, string, int> people[i];       // Type: Tuple<int, string, int> people[i].Item1; // Type: int 
like image 174
voithos Avatar answered Sep 27 '22 20:09

voithos


You're indexing the wrong object. people is the array that you want to index, not Item1. Item1 is simply a value on any given object in the people collection. So you'd do something like this:

for (int i = 0; i < people.Count; i++) {     Console.WriteLine(people[i].Item1); //the int     Console.WriteLine(people[i].Item2); //the string     Console.WriteLine(people[i].Item3); //the int        } 

As an aside, I highly recommend you create an actual object to hold these values instead of a Tuple. It makes the rest of the code (such as this loop) much more clear and easy to work with. It could be something as simple as:

class Person {     public int ID { get; set; }     public string Name { get; set; }     public int SomeOtherValue { get; set; } } 

Then the loop is greatly simplified:

foreach (var person in people) {     Console.WriteLine(person.ID);     Console.WriteLine(person.Name);     Console.WriteLine(person.SomeOtherValue); } 

No need for comments explaining what the values mean at this point, the values themselves tell you what they mean.

like image 44
David Avatar answered Sep 27 '22 21:09

David