-1

I have an index which from a dictionary get the column string to order by in Linq

dict.Add(0, "seleccionado");
dict.Add(1, "IdPedido");
dict.Add(2, "FechaPedido");
dict.Add(3, "NSerie");
dict.Add(4, "Importe");

I have, too, a list of Orders and I need to get the order (DESC/ASC) when I click in the column of the field.

Mmy idea was to do the Linq in one line because I will pass two parameters: the string field to order and the direction (ASC/DESC).

How can I do it in Linq?

WHAT I TRIED:

pedidos.OrderBy(x => x.seleccionado);

seleccionado is the object of the class, but in my case I will give an string instead of the object field name.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Dave
  • 7,028
  • 11
  • 35
  • 58

2 Answers2

3

If I understand the question, you're asking how to sort a collection by a field, where the field is chosen by the user.

In this case, why not store the lambda in the dictionary?

dict.Add(0, x => x.seleccionado);
dict.Add(1, x => x.IdPedido);

// etc.
Roger Lipscombe
  • 89,048
  • 55
  • 235
  • 380
0

https://stackoverflow.com/a/2728432/3825634

This has been answered before.

There are dynamic linq libraries available. They will allow you to build up parts of your linq queries dynamically with strings.

Community
  • 1
  • 1
Dan
  • 89
  • 7