2016-05-27 11 views
0

私は私のクラスに異なる値を書きます、私は私のクラスの値を取得したいと思います。デバッグ出力は私を示していますC#リスト /リスト<class>値を取得

値:List.dataインデックス0 値:私は私のクラスのプロパティの実際の値を取得する方法List.data指数1

私のコード例:あなたはちょうどそれがデフォルトでちょうどクラスの名前を返しますobjextのToString()メソッドを呼び出しますプリントアウトするためのオブジェクトを置く

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Drawing; 
using System.Diagnostics; 

namespace List 
{ 
    class data 
    { 
     public string name { get; set; } 
     public Rectangle rect { get; set; } 
    } 

    class Program 
    { 
     static void Main(string[] args) 
     { 

      data dat1 = new data(); 
      List<data> listdat = new List<data>(); 
      dat1.name = "test1"; 
      dat1.rect = new Rectangle(10, 10, 10, 10); 
      listdat.Add(dat1); 

      data dat2 = new data(); 
      dat2.name = "test2"; 
      dat2.rect = new Rectangle(20, 20, 20, 20); 
      listdat.Add(dat2); 

      data dat3 = new data(); 
      dat3.name = "test3"; 
      dat3.rect = new Rectangle(30, 30, 30, 30); 
      listdat.Add(dat3); 

      listdat.RemoveAt(1); 
      foreach (var item in listdat) 
      { 
       //This will yield the proper index that you are currently on 
       int index = listdat.IndexOf(item); 
      } 

      foreach (var item in listdat.Select((value, index) => new { Value = value, Index = index })) 
      { 
       //Get the value through item.Value; 
       var currentValue = item.Value; 
       //Get the index through item.Index; 
       int currentIndex = item.Index; 
       Debug.WriteLine("Value: {0} Index {1}", currentValue, currentIndex); 
      } 
      int i = 0; 
     } 
    } 
} 

答えて

1

- 私はあなたが-statementこの奇妙なSelectを使用する理由不思議ではなく、また、あなたのインデックスを与えるためのループ古き良きスタイル:

for(int i = 0; i < listdat.Count; i++) 
{ 
    var currentValue = listdat[i].Name; 
    int currentIndex = item.Index; 
    Debug.WriteLine("Value: {0} Index {1}", currentValue, i); 
} 

あなたも簡単に行って、あなたの現在のインスタンスlistdat[i]とyou'reのプロパティを(おそらくnameあなたのケースで)アクセス、あなたのdata級・コードを変更する必要がドント。

Btw。変数indexはすべてのループでリセットされますが、決して読み込まれることはありませんが、次のコードは役に立ちません。

foreach (var item in listdat) 
{ 
    //This will yield the proper index that you are currently on 
    int index = listdat.IndexOf(item); 
} 
1

何か異なる出力をしたい場合は、オーバーライドする必要があります。あなたは、たとえばdataクラスにこれを追加することができます

public override string ToString() 
{ 
    return name; 
} 
関連する問題