tags:

views:

91

answers:

2

Assume a method declared as the following:

public static string GetString<T>(IEnumerable<T> collection, string theProperty)

How can I, using reflection, return the value of property theProperty of the first element in the generic collection? (using Linq's First() method).

Thanks

+4  A: 
public static string GetString<T>(IEnumerable<T> collection, string theProperty)
{
  return (string)(typeof(T)).GetProperty(theProperty).GetValue(collection.First(), null));
}
Matthew Flaschen
+3  A: 

Error checking omitted for brevity:

return (string) typeof(T).GetProperty(theProperty).GetValue(collection.First(), null);
arul