ebelair ebelair - 1 month ago 24
C# Question

Linq dynamic orderby not working

I don't know how to make a dynamic Linq query.

This is working:

var query = from article in context.DP_ARTICLES
orderby article.ART_NUM descending
select new ArticleItem() { Article = article };


But this is not working:

var query = from article in context.DP_ARTICLES
orderby("ART_NUM DESC")
select new ArticleItem() { Article = article };


EDIT:

The goal is to order a listview columns, so in my method i get the sql column name as string parameter(eg ART_NUM). So the best is to use it directly in my query instead of make a switch ...

Answer

The dynamic methods only work when using the method syntax of the calls, it will not work when using the query syntax.

var query = context.DP_ARTICLES
    .OrderBy("ART_NUM DESC")
    .Select(a => new ArticleItem { Article = a });