Is it possible to attach methods to C# anonymous types?
It would be desirable to be able to provide e.g. comparison functions (i.e. with lambdas) for an ano开发者_如何学Pythonnymous type, so that they can be sorted by a set of criteria. Is that possible in C#?
No, just make a regular class instead.
Possible related: Can a C# anonymous class implements an interface?
Lambdas are implicitly convertable to System.Comparison`1:
var anons = (new[] {new {a = 3}, new {a = 4}, new {a = 2}}).ToList();
anons.Sort((x, y) => (x.a - y.a));
You can also use the LINQ OrderBy
extension method to sort anonymous types.
var anons = new[] {new {a = 3}, new {a = 4}, new {a = 2}};
var sorted = anons.OrderBy(s => s.a);
Yes. You must declare the type of the comparison function:
var anon = new {comparator = (Func<string, int>) (s => s.Length)};
精彩评论