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 }
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With