Getting a property value using a LINQ expression
本问题已经有最佳答案,请猛点这里访问。
Possible Duplicate:
Get property value from string using reflection in C#
号
我正在尝试编写一个通用方法,以允许我在迭代集合时指定要检索的属性:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | 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); } } } |
基本上,我希望遍历stats集合,并写出指定属性的值。我假设我可以使用LINQ表达式来实现这一点,但我不知道如何实现!
使用IEnumerable<>。select():
1 2 3 4 5 6 | var props = collection.Select(x => x.Property); foreach (var p in props) { Console.WriteLine(p.ToString()); } |
按年份顺序获取值:
1 2 3 4 5 6 7 8 | foreach (double value in from stat in stats where years.Contains(stat.InformationYear) orderby stat.InformationYear select stat.Property) { Console.WriteLine(value); } |
号
如果我理解您的问题,您需要写出InformationYear属性的值,因此您的LINQ表达式如下:
1 2 3 4 5 6 | foreach (double value in from stat in stats select stat.InformationYear) { Console.WriteLine(value); } |