1

Possible Duplicate:
Get property value from string using reflection in C#

I am trying to write a generic method to allow me to specific a property to retrieve when iterating through a collection:

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

Basically, I want to iterate through the stats collection, and write out a specified property's value. I assume that I can use LINQ expressions to do this, but I have no idea how!

Community
  • 1
  • 1
ScottD
  • 173
  • 5
  • 15
  • sorry for the question, but what's "value" variable? – stefano m Sep 25 '12 at 09:45
  • 1
    You don't use LINQ to get the value of a property like this; you use *reflection*. There should be lots of information if you search using this term. – Jon Sep 25 '12 at 09:49
  • Your code does not match much what you explain, which property you want to get value? – cuongle Sep 25 '12 at 09:58
  • value is a placeholder for whatever the value of the property is. – ScottD Sep 25 '12 at 10:29
  • I know how to use reflection to get the property, but I would prefer not to have to use magic strings to get the value of the property. – ScottD Sep 25 '12 at 10:36

3 Answers3

2

Use IEnumerable<>.Select():

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

foreach (var p in props)
{
  Console.WriteLine(p.ToString());
}
rkrahl
  • 1,159
  • 12
  • 18
1

Gets you the values in order of year:

foreach (double value in
    from stat in stats
    where years.Contains(stat.InformationYear)
    orderby stat.InformationYear
    select stat.Property)
{
    Console.WriteLine(value);
}
MrFox
  • 4,852
  • 7
  • 45
  • 81
0

If I understand you question, you need to write out InformationYear property's value,so your LINQ expression is as follows :

  foreach (double value in
        from stat in stats
        select stat.InformationYear)
    {
        Console.WriteLine(value);
    }
HichemSeeSharp
  • 3,240
  • 2
  • 22
  • 44