© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•4y ago•
8 replies
no >> body

✅ Replacing Linq.Dynamic

I am trying to replace the System.Linq.Dynamic.Core package with regular LINQ in my ASP.NET Core application. I have a method that applies filtering, sorting, and pagination to a queryable collection of entities, using the System.Linq.Dynamic.Core package. Here is the code from my method:

if (!string.IsNullOrEmpty(filter))
{
    var filterVal = (JObject)JsonConvert.DeserializeObject(filter);
    var t = new T();
    foreach (var f in filterVal)
        if (t.GetType().GetProperty(f.Key)?.PropertyType == typeof(string))
            entityQuery = entityQuery.Where($"{f.Key}.Contains(@0)", f.Value.ToString());
        else
            entityQuery = entityQuery.Where($"{f.Key} == @0", f.Value.ToString());
}

var count = entityQuery.Count();

if (!string.IsNullOrEmpty(sort))
{
    var sortVal = JsonConvert.DeserializeObject<List<string>>(sort);
    var condition = sortVal.First();
    var order = sortVal.Last() == "ASC" ? "" : "descending";
    entityQuery = entityQuery.OrderBy($"{condition} {order}");
}
if (!string.IsNullOrEmpty(filter))
{
    var filterVal = (JObject)JsonConvert.DeserializeObject(filter);
    var t = new T();
    foreach (var f in filterVal)
        if (t.GetType().GetProperty(f.Key)?.PropertyType == typeof(string))
            entityQuery = entityQuery.Where($"{f.Key}.Contains(@0)", f.Value.ToString());
        else
            entityQuery = entityQuery.Where($"{f.Key} == @0", f.Value.ToString());
}

var count = entityQuery.Count();

if (!string.IsNullOrEmpty(sort))
{
    var sortVal = JsonConvert.DeserializeObject<List<string>>(sort);
    var condition = sortVal.First();
    var order = sortVal.Last() == "ASC" ? "" : "descending";
    entityQuery = entityQuery.OrderBy($"{condition} {order}");
}


I'm tried something like this
entityQuery = entityQuery.OrderBy(e => e.GetType().GetProperty(condition).GetValue(e));
entityQuery = entityQuery.OrderBy(e => e.GetType().GetProperty(condition).GetValue(e));

But this obviously doesn't work.
Is there a way to sort a queryable collection of entities based on a property, using regular LINQ and Entity Framework Core? Downloading all entities to the memory and sorting them in the asp.net core app is not an option.
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

Efcore Dynamic Linq, AND and OR
C#CC# / help
4mo ago
Dynamic EF Core LINQ Queries for API Consumption
C#CC# / help
7mo ago
LINQ
C#CC# / help
2y ago
❔ LINQ
C#CC# / help
3y ago