我正在尝试编写一个通用方法,以允许我在迭代集合时具体检索属性:
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表达式来执行此操作,但我不知道如何!
答案 0 :(得分:2)
使用IEnumerable&lt;&gt; .Select():
var props = collection.Select(x => x.Property);
foreach (var p in props)
{
Console.WriteLine(p.ToString());
}
答案 1 :(得分:1)
按年份顺序获取值:
foreach (double value in
from stat in stats
where years.Contains(stat.InformationYear)
orderby stat.InformationYear
select stat.Property)
{
Console.WriteLine(value);
}
答案 2 :(得分:0)
如果我理解你的问题,你需要写出InformationYear属性的值,所以你的LINQ表达式如下:
foreach (double value in
from stat in stats
select stat.InformationYear)
{
Console.WriteLine(value);
}