C sharp - How can I sort by a property of a dynamic object in c#

 
Vista:

How can I sort by a property of a dynamic object in c#

Publicado por Asbel Santana (1 intervención) el 28/09/2023 19:05:58
I have the following function to sort an object by a property and sort the result.



But I can't search and sort by a property of a subclass  

"id": 10651,

            "requestNo": "tradeNo1",

            "entryDateDGII": "2023-08-21T13:51:02.166",

            "entryDate": "2023-08-21T13:51:02.166",

            "referalChannelId": 78,

            "referalChannel": "App Movil",

            "complaints": [

                {

                    "documentTypeId": 2,

                    "documentType": "Pasaporte",

                    "number": "sadas13211515",

                    "name": "bnombre",

                    "surnames": "Denunciante apellido"

                }

            ],If it is by the Id it works but if it is by documentType that is inside an object it does not search for thatpublic static List<T> ApplyOrdering<T>(List<T> list, string orderBy, OrderDirectionEnum orderDirection)

        {

            if (!string.IsNullOrEmpty(orderBy))

            {

                var orderByProperty = typeof(T).GetProperty(orderBy, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);

                if (orderByProperty != null)

                {

                    bool isDescending = orderDirection == OrderDirectionEnum.Desc;

                    list = isDescending ? list.OrderByDescending(item => orderByProperty.GetValue(item)).ToList() : list.OrderBy(item => orderByProperty.GetValue(item)).ToList();

                }

                else

                {

                    throw new KeyNotFoundException("Campo de ordenamiento no válido");

                }

            }

            return list;

        }
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder

How can I sort by a property of a dynamic object in c#

Publicado por algun juan soler en el mundo (1 intervención) el 04/10/2023 22:11:30
lo que debes hacer es usar refexion dos veces, es decir

var obj = tu objeto;

var propery = typeof(T).GetProperty(orderBy, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);

luego var result = property.GetValue(obj);

var thenProperty = property.GetType().GetProperty(orderBy, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);

var result2 = thenProperty.GetValue(result);
y eso lo devuelves en el orderBy;
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar