2012-09-25 34 views
1

可能重複:
Get property value from string using reflection in C#獲得使用LINQ表達式的屬性值

我想編寫一個通用的方法,讓我具體屬性檢索通過迭代時收集:

private void WriteStatisticsRow<T>(ICollection<InstitutionStatistics> stats, 
    ICollection<short> years, 
    string statisticsName, 
    string rangeName) where T : struct 
{ 
    Console.WriteLine(statisticsName); 

    foreach (short yr in years) 
    { 
     var stat = stats.SingleOrDefault(s => s.InformationYear == yr); 

     if (stat != null) 
     { 
      if (typeof(T) == typeof(double)) 
      { 
       Console.WriteLine(value, format: "0.0"); 
      } 
      else 
      { 
       Console.WriteLine(value); 
      } 
     } 
     else 
     { 
      Console.WriteLin(string.Empty); 
     } 
    } 
} 

基本上,我想遍歷統計集合,並寫出一個指定的屬性值。我假設我可以使用LINQ表達式來做到這一點,但我不知道如何!

+0

對不起這個問題,但是什麼是「value」變量? –

+1

您不使用LINQ來獲取像這樣的屬性的值;你使用*反射*。如果使用此術語進行搜索,應該有很多信息。 – Jon

+0

您的代碼與您所解釋的內容不符,您希望獲得哪個屬性的價值? –

回答

2

使用的IEnumerable <>。選擇():

var props = collection.Select(x => x.Property); 

foreach (var p in props) 
{ 
    Console.WriteLine(p.ToString()); 
} 
1

獲取你爲了一年的值:

foreach (double value in 
    from stat in stats 
    where years.Contains(stat.InformationYear) 
    orderby stat.InformationYear 
    select stat.Property) 
{ 
    Console.WriteLine(value); 
} 
0

如果我理解你的問題,你需要寫出來InformationYear屬性的值,所以你的LINQ表達式如下:

foreach (double value in 
     from stat in stats 
     select stat.InformationYear) 
    { 
     Console.WriteLine(value); 
    }