Dynamic LINQ with System.Linq.Dynamic.Core

How System.Linq.Dynamic.Core can be used to parse strings in LINQ dynamically

Home DailyDrop

Daily Knowledge Drop

The third-party, open source library System.Linq.Dynamic.Core extends LINQ functionality allowing dynamic, string based LINQ queries to be parsed, resulting in operations identical to regular LINQ.

Examples

In all of the below examples, the following snippet of code is used to get a sample collection of Song entities:

IEnumerable<Song> GetSongs()
{
    return new[]
    {
        new Song("Learn to Fly", "Foo Fighters", 245),
        new Song("Everlong", "Foo Fighters", 312),
        new Song("Bigger than my Body", "John Mayer", 281),
    };
};

public record Song(string Name, string Artist, int LengthInSeconds);

The extension methods System.Linq.Dynamic.Core offer are available on the IQueryable interface. As such in the examples the IEnumerable<Song> returned from the GetSongs method is required to be converted to IQueryable<Song> using the AsQueryable method before the extension methods are available.

Below come common use cases are shown, but the library does offer a lot more functionality - see the references links below for more information on the library.


Select

System.Linq.Dynamic.Core can be used to dynamically Select a property value from a collection of entities:

// using traditional LINQ
List<string> namesLinq = songs
  .Select(s => s.Name)
  .ToList();

// dynamically specifying the property to be returned
List<string> nameDynamic = songs
  .AsQueryable()
  .Select("Name")
  .ToDynamicList<string>();

A anonymous or dynamic entity can also be Selected out of the collection dynamically:

// traditional
var nameArtistLinq = songs
  .Select(s => new { s.Name, s.Artist })
  .ToList();

// dynamic
List<dynamic> nameArtistDynamic = songs
  .AsQueryable()
  .Select("new { Name, Artist}")
  .ToDynamicList();

This is very powerful, allowing the columns to be selected to be determined at runtime.


Filtering

The library also provides the ability to dynamically filter a collection of records:

// traditional
List<Song> filterLinq = songs
  .Where(x => x.Artist == "Foo Fighters")
  .ToList();

// dynamic
string column = "Artist";
string value = "Foo Fighters";
List<Song> filterDynamic = songs
  .AsQueryable()
  .Where($"{column} == \"{value}\"")
  .ToList();

Again, very powerful as it allows the filter criteria to be be generated at runtime.

Outputting the result of the filtering for each technique yields the same result:

Console.WriteLine(filterLinq.Count());
Console.WriteLine(filterDynamic.Count());

// ouput:
// 2
// 2

Ordering

The library also offers the ability to dynamically order a collection:

// traditional LINQ ordering
List<Song> orderLinq = songs
  .OrderBy(s => s.LengthInSeconds)
  .ToList();
  
List<Song> orderDescLinq = songs
  .OrderByDescending(s => s.LengthInSeconds)
  .ToList();

// dynamic ordering
List<Song> orderDynamic = songs
  .AsQueryable()
  .OrderBy("LengthInSeconds")
  .ToList();

List<Song> orderDescDynamic = songs
  .AsQueryable()
  .OrderBy("LengthInSeconds desc")
  .ToList();

The functionality the library offers is very easy and intuitive to use, as one can see from the above examples.


Notes

This is a very powerful library, and more functionality than described here. If dynamic LINQ is not required, I do not recommend replacing traditional strongly-typed LINQ with this as a based, however in cases where flexibility to change the LINQ at runtime is required, this library is incredibly powerful.

If this is of interest it is definitely recommended to check out the Dynamic LInq reference link below for more information.


References

Using Dynamic LINQ With System.Linq.Dynamic.Core Library
Dynamic LINQ

Daily Drop 212: 29-11-2022

At the start of 2022 I set myself the goal of learning one new coding related piece of knowledge a day.
It could be anything - some.NET / C# functionality I wasn't aware of, a design practice, a cool new coding technique, or just something I find interesting. It could be something I knew at one point but had forgotten, or something completely new, which I may or may never actually use.

The Daily Drop is a record of these pieces of knowledge - writing about and summarizing them helps re-enforce the information for myself, as well as potentially helps others learn something new as well.
c# .net linq dynamic