I need to get names of all properties of anonymous type exactly in the order they are declared.
To get them, I can use Type.GetProperties
method. It seems to return properties in "correct" order, but according to MSDN I cannot depend on it, because that order might vary.
I also found TypeInfo.DeclaredProperties
property which gives me result I expect, but I cannot found any info whether the order is guaranteed or not (at least MSDN doesn't explicitly state it's not guaranteed).
Or is there any other way? It's probably irrelevant, but the anonymous type is actually part of Expression
. But I'm not aware of anything in Expression Trees API which can help.
I'm targeting .NET Standard 2.0 and it should work on full .NET framework, .NET Core and Mono/Xamarin.
Sample code:
static void Main(string[] args)
{
Foo(() => new { Lorem = 1, Ipsum = 2, Dolor = "sit amet" });
}
static void Foo<T>(Expression<Func<T>> expression)
{
var node = (NewExpression)expression.Body;
// seems to work, but GetProperties doesn't guarantee order according to MSDN
var names1 = node.Type.GetProperties().Select(p => p.Name).ToArray();
// names1 = "Lorem", "Ipsum", "Dolor"
// seems to work, but is it "bulletproof"?
var names2 = node.Type.GetTypeInfo().DeclaredProperties.Select(p => p.Name).ToArray();
// names2 = "Lorem", "Ipsum", "Dolor"
}
Edit: I purposely didn't write exactly why I need it, because I find my specific scenario unnecessarily complicated to explain and wanted to keep the question simple. Long story short - I'm exploring possibilities for micro-ORM API based on parsing expression trees. Not my original case, but here is an example of hypothetical use case where knowing the order is important (I'm not saying such API for sorting is good idea! I just want to know whether something like this is possible):
// translates to SELECT Column1, Column2 FROM Table ORDER BY Column3, Column1
db.From<Table>()
.Select((x) => new { x.Column1, x.Column2 })
.OrderBy((x) => new { x.Column3, x.Column1 });