Name of the Linq Dynamics column?

Asked

Viewed 57 times

0

I have a column that will receive the orderBy dynamically, by example:

_context.Tabela
   .Where(p => 
        p.colunaA.Contains(searchBy) ||
        p.colunaB.Contains(searchBy) ||
        p.colunaC.Contains(searchBy) ||
        p.colunaD.Contains(searchBy)
   )
   .OrderByDescending(p => p.colunaA)

how to place this column p => p.colunaA dynamic? Can be columns A, B,C or D. I tested several forms and could not reach a SelectedColumn.

  • How many columns are there? how do you define which column is to be sorted? has how to explain it better?

2 answers

0

There is a package called System.Linq.Dynamic that has an option to pass the column name as string, this should solve your problem:

var coluna = "colunaDinamica";
....
.OrderByDescending(coluna);

You can even enter the order, for example "nameDaColuna DESC"

I use in . Net Core, the package is this: https://www.nuget.org/packages/System.Linq.Dynamic.Core

  • I did it the way I answered it, but I tested it that way I answered it and it worked perfectly, thank you!

-1

I ended up finding a simple way:

var propertyInfo = typeof(Resultados).GetProperty("nomeDaColuna");
_context.Tabela.AsEnumerable().OrderByDescending(x => propertyInfo.GetValue(x, null))

Net core 3+ as I was returning a list I needed Asenumerable(), previous I did not test to confirm the need

  • the way you did is wrong, because it causes a bad performance, all this has to be done before materializing the result, The way you did carries all the load and then orders, it is better to already come ordered, IE, you are using wrong.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.