No, GetProperty("username")
returns the PropertyInfo
associated with with the username
property. This should be the same object for all values in your collection (assuming they are the same type). To get the value of this property for each object you'd have to call GetValue
and pass in an instance of the object whose property value you'd like to return, like this:
foreach (var entry in mainTable.OrderBy(key => key.Value.GetType().GetProperty("username").GetValue(key.Value, null))
{
...
}
Note the use of implicit typing with the var
keyword for brevity.
However, I really wouldn't do this unless you really have to; using reflection is slow compared to direct property access.
Also note, if you're trying to run this against a Linq-to-Entities provider or similar, this simply won't work. That's because the Linq provider needs to translate the expression you provide to a SQL query, and GetType
, GetProperty
, and GetValue
simply don't have a SQL equivalent (at least not one that the Linq provider can use).
Also note, in your example, username
is actually a field rather than a property. In that case, you'd use GetField("username")
instead (which returns a FieldInfo
):
foreach (var entry in mainTable.OrderBy(key => key.Value.GetType().GetField("username").GetValue(key.Value))
{
...
}
Alternatively, you could simply use dynamic
, which will allow you to write something that looks like a normal property / field access, but will in fact cause the compiler to emit reflection code similar to what's described above:
foreach (var entry in mainTable.OrderBy(key => ((dynamic)key.Value).username)
{
...
}