How to perform a LINQ where clause with a dynamic column

I am attempting to use System.Linq.Dynamic.Core (https://github.com/StefH/System.Linq.Dynamic.Core) in order to create dynamic queries.

Following the example given on the github page, I have tried the following

lstContacts = lstContacts.Where("@0 == true", "active");

However I get the following result: 'active is not a valid value for Boolean

Upvotes: 2

Views: 349

Answers (1)

cnom
cnom

Reputation: 3241

Reference this library:

using System.Linq.Dynamic;

And make your query like that:

string columnName = "active";

var lstContacts = lstContacts.Where(columnName + " == true");

Here is a working example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic;

public class Program
{
    public static void Main()
    {
        var lstContacts = new List<Contact>{
            new Contact{Id = 1, Active = true, Name = "Chris"}, 
            new Contact{Id = 2, Active = true, Name = "Scott"}, 
            new Contact{Id = 3, Active = true, Name = "Mark"}, 
            new Contact{Id = 4, Active = false, Name = "Alan"}};

        string columnName = "Active";
        List<Contact> results = lstContacts.Where(String.Format("{0} == true", columnName)).ToList();
        foreach (var item in results)
        {
            Console.WriteLine(item.Id.ToString() + " - " + item.Name.ToString());
        }
    }
}

public class Contact
{
    public int Id
    {
        get;
        set;
    }

    public bool Active
    {
        get;
        set;
    }

    public string Name
    {
        get;
        set;
    }
}

You can experiment with this .net-fiddle-here

Upvotes: 2

Related Questions