我正在尝试使用System.Linq.Dynamic.Core(https://github.com/StefH/System.Linq.Dynamic.Core)来创建动态查询。
按照github页面上给出的示例,我尝试了以下方法
lstContacts = lstContacts.Where("@0 == true", "active");
但是我得到以下结果: 'active不是布尔值的有效值
答案 0 :(得分:2)
参考该库:
using System.Linq.Dynamic;
然后像这样进行查询:
string columnName = "active";
var lstContacts = lstContacts.Where(columnName + " == true");
这是一个有效的示例:
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;
}
}
您可以尝试使用此.net-fiddle-here