2013-07-23 4 views
16

У меня есть список кортежей:Получить определенный элемент из списка кортежей с #

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  
     } 
+0

людей [я] .Item1, люди [я] .Item2, люди [я] .Item3 –

ответ

15

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 
+1

Quickest ответ получает приз – Wayneio

1

Попробуйте это:

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  
    } 
1

Вы должны переместить индексатор немного назад:

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  
} 
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); 
} 
9

Вы индексировать неправильный объект. 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); 
} 

Нет необходимости для комментариев, объясняющих то, что значения означают в этом пункте, значения говорят сами, что они означают ,

+0

Хороший совет, спасибо – Wayneio

2

Вы должны изменить, где ваш индексатор, вы должны поставить его так:

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  
} 

Там вы идете !!

0
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()); 
    } 

} 
Смежные вопросы