我有一个元组列表:
List<Tuple<int, string, int>> people = new List<Tuple<int, string, int>>();
Run Code Online (Sandbox Code Playgroud)
使用a dataReader,我可以使用各种值填充此列表:
people.Add(new Tuple<int, string, int>(myReader.GetInt32(4), myReader.GetString(3), myReader.GetInt32(5)));
Run Code Online (Sandbox Code Playgroud)
但是,我如何循环,获得每个单独的价值.例如,我可能想要阅读特定人员的3个细节.假设有一个ID,一个名字和一个电话号码.我想要以下内容:
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
}
Run Code Online (Sandbox Code Playgroud)
voi*_*hos 26
people是一个列表,让你索引列表中第一个,然后你可以引用任何你想要的物品.
for (int i = 0; i < people.Count; i++)
{
people[i].Item1;
// Etc.
}
Run Code Online (Sandbox Code Playgroud)
请记住您正在使用的类型,这些类型的错误将是少之又少.
people; // Type: List<T> where T is Tuple<int, string, int>
people[i]; // Type: Tuple<int, string, int>
people[i].Item1; // Type: int
Run Code Online (Sandbox Code Playgroud)
Dav*_*vid 13
您正在索引错误的对象. people是要索引的数组,而不是Item1. Item1只是people集合中任何给定对象的值.所以你会做这样的事情:
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
}
Run Code Online (Sandbox Code Playgroud)
顺便说一句,我强烈建议您创建一个实际对象来保存这些值而不是a Tuple.它使代码的其余部分(例如此循环)更加清晰且易于使用.它可能很简单:
class Person
{
public int ID { get; set; }
public string Name { get; set; }
public int SomeOtherValue { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
然后循环大大简化:
foreach (var person in people)
{
Console.WriteLine(person.ID);
Console.WriteLine(person.Name);
Console.WriteLine(person.SomeOtherValue);
}
Run Code Online (Sandbox Code Playgroud)
无需评论解释此时值的含义,值本身会告诉您它们的含义.