简体   繁体   English

如何使用动态列执行 LINQ where 子句

[英]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.我正在尝试使用 System.Linq.Dynamic.Core ( https://github.com/StefH/System.Linq.Dynamic.Core ) 来创建动态查询。

Following the example given on the github page, I have tried the following按照github页面上给出的示例,我尝试了以下操作

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

However I get the following result: 'active is not a valid value for Boolean但是我得到以下结果:'active is not a valid value for Boolean

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你可以在这里试验这个.net-fiddle-here

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM