There is a class that contains a large number of fields (> 50). There is a collection that contains elements of this class. You need to implement a method that sorts this collection by the specified field. A field is set by passing a string with the name of the desired field to the method. In this case, the class may later be added to the class. The method should sort the collection by new fields without changing the method itself. Using IComparer and reflection is not suitable. Is there any other way to access the field of an object by its name?

Clarification: IComparer cannot be implemented for the class itself, comparison is available for field class types.

  • 2
    “Using ... reflection is not suitable” and “accessing the field of an object by its name” - Better, of course, to suffer. Tov. Sukhov, "White Sun of the Desert" - Igor
  • Uh ... And who put you this task? I join the previous speaker: you yourself create problems for yourself. - VladD
  • Why exactly does reflection not fit? If the problem is in speed, then it can be optimized through Reflection.Emit or through Linq.Expressions, it will be without an overhead at all after the first launch. - Oleg Nechitaylo
  • @ Oleg Nechitailo can give an example of using Expressions? - Vitaly Efimov

1 answer 1

in general, your task has no solution even through reflection, since sorting requires a guarantee that the field types allow comparison, i.e. implement IComparable , here, alas, there are no alternatives.

With so many fields, it makes sense to think about replacing an insane number of fields with something like a Dictionary<string, IComparable> . In this case, you get access to the values ​​by name, which you lack so much. Plus, as a bonus, you can avoid wasting memory on storing "empty" values, and painlessly adding any number of additional named values. With proper implementation, you can get a very good performance. Well, with the sorting method, there is no need for too much wisdom, you can use the overloads of standard interfaces.

The idea is peeped here.

  • I also tended to use the dictionary, but I could not turn my thoughts into something concrete. - Vitaly Efimov