Получить определенный элемент из списка кортежей С#
У меня есть список кортежей:
List<Tuple<int, string, int>> people = new List<Tuple<int, string, int>>();
Используя dataReader
, я могу заполнить этот список различными значениями:
people.Add(new Tuple<int, string, int>(myReader.GetInt32(4), myReader.GetString(3), myReader.GetInt32(5)));
Но тогда как я прохожу, получая каждое индивидуальное значение. Например, я могу прочитать три детали для конкретного человека. Допустим, есть идентификатор, имя и номер телефона. Я хочу что-то вроде следующего:
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
}
Ответы
Ответ 1
people
- это список, поэтому вы указываете в список первый, а затем можете ссылаться на любой элемент, который вы хотите.
for (int i = 0; i < people.Count; i++)
{
people[i].Item1;
// Etc.
}
Просто имейте в виду типы, с которыми вы работаете, и таких ошибок будет немного и далеко.
people; // Type: List<T> where T is Tuple<int, string, int>
people[i]; // Type: Tuple<int, string, int>
people[i].Item1; // Type: int
Ответ 2
Вы индексируете неправильный объект. 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
}
В стороне, я настоятельно рекомендую вам создать фактический объект для хранения этих значений вместо Tuple
. Это делает остальную часть кода (например, этот цикл) более понятной и простой в использовании. Это может быть что-то простое:
class Person
{
public int ID { get; set; }
public string Name { get; set; }
public int SomeOtherValue { get; set; }
}
Тогда цикл значительно упрощается:
foreach (var person in people)
{
Console.WriteLine(person.ID);
Console.WriteLine(person.Name);
Console.WriteLine(person.SomeOtherValue);
}
Нет необходимости в комментариях, объясняющих, что означают значения в данный момент, сами значения говорят вам, что они означают.
Ответ 3
Это все, что вы ищете?
for (int i = 0; i < people.Count; i++)
{
Console.WriteLine(people[i].Item1);
Console.WriteLine(people[i].Item2);
Console.WriteLine(people[i].Item3);
}
или используя foreach
:
foreach (var item in people)
{
Console.WriteLine(item.Item1);
Console.WriteLine(item.Item2);
Console.WriteLine(item.Item3);
}
Ответ 4
Вам нужно изменить, где находится ваш индекс, вы должны сделать следующее:
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
}
Там вы идете!
Ответ 5
Попробуйте следующее:
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
}
Ответ 6
Вам нужно немного переместить указатель:
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
}
Ответ 7
class Ctupple
{
List<Tuple<int, string, DateTime>> tupple_list = new List<Tuple<int, string, DateTime>>();
public void create_tupple()
{
for (int i = 0; i < 20; i++)
{
tupple_list.Add(new Tuple<int, string, DateTime>(i, "Dump", DateTime.Now));
}
StringBuilder sb = new StringBuilder();
foreach (var v in tupple_list)
{
sb.Append(v.Item1);
sb.Append(" ");
sb.Append(v.Item2);
sb.Append(" ");
sb.Append(v.Item3);
sb.Append(Environment.NewLine);
}
Console.WriteLine(sb.ToString());
int j = 0;
}
public void update_tupple()
{
var vt = tupple_list.Find(s => s.Item1 == 10);
int index = tupple_list.IndexOf(vt);
vt = new Tuple<int, string, DateTime>(vt.Item1, "New Value" , vt.Item3);
tupple_list.RemoveAt(index);
tupple_list.Insert(index,vt);
StringBuilder sb = new StringBuilder();
foreach (var v in tupple_list)
{
sb.Append(v.Item1);
sb.Append(" ");
sb.Append(v.Item2);
sb.Append(" ");
sb.Append(v.Item3);
sb.Append(Environment.NewLine);
}
Console.WriteLine(sb.ToString());
}
}