'Dynamic Columns from List using LINQ

I need help to get the columns from list dyanmic using LINQ. Like this,

List<DashBoard> dashboardlist = (List<DashBoard>)objList;

objList = (from obj in dashboardlist 
          select new { obj.EprotexStatus, obj.RecReference, obj.RecDescription, 
                       obj.RecDate, obj.ModifiedDate, obj.RectypeDesc 
          }).ToList();

above is working fine to return columns from list using LINQ.

But I want specific columns from list in following process

List<DashBoard> dashboardlist = (List<DashBoard>)objList;
string strColumns = "RecDate,ModifiedDate";
objList = (from obj in dashboardlist 
           select new { strColumns }
          ).ToList();

Above statement i want get two columns only based on string columns variable.



Solution 1:[1]

You can achieve this using the DynamicLinq package.

using System.Linq.Dynamic.Core;

List<object> result = dashboardlist.Select("new {RecDate,ModifiedDate}").ToList();

Here's a stand alone sample that works in a plain console application (assuming .NET 6). First, create a console application. On the command line:

dotnet new console
dotnet add package System.Linq.Dynamic.Core

Then, replace Program.cs with this:

using System.Linq.Dynamic.Core;

var people = new[]
{
    new Person { FirstName = "John", LastName = "Doe", BirthDate = new DateTime(1970,1,1)},
    new Person { FirstName = "Jane", LastName = "Bar", BirthDate = new DateTime(1970,1,1)},
}.AsQueryable();

var query = people.Where("LastName = \"Doe\"").Select("new { FirstName, BirthDate }");

foreach (dynamic item in query)
    Console.WriteLine($"{item.FirstName}'s birthdate is {item.BirthDate}");

internal class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public DateTime BirthDate { get; set; }
}

Finally, use dotnet run and see the result. It should output John's birthdate is 1/01/1970 0:00:00.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1