是否可以搜索IQueryable
public static IQueryable<object> SearchAllFields(IQueryable<object> query, string term)
{
query = query.Where(q => q.Property1 == term);
query = query.Where(q => q.Property2 == term);
query = query.Where(q => q.Property3 == term);
return query;
}
假设我想将搜索词与对象可能具有的每个属性进行比较,而不知道对象可能具有哪些属性。
修改:
我正在尝试创建一个通用的DataTable解决方案,以显示可能需要的任何表格信息(订单,书籍,客户等)
为了测试我在数据库中使用ApplicationLogs表的概念。 DataTable如下所示:
让我们说在输入该搜索框时,我想在可能显示的所有列中搜索该值。填充表格的查询:
IQueryable<object> query = (from log in db.ApplicationLog
orderby log.LogId descending
select new
{
LogId = log.LogId,
LogDate = log.LogDate.Value,
LogLevel = log.LogLevelId == 1 ? "Information" : log.LogLevelId == 2 ? "Warning" : "Error",
LogSource = log.LogSourceId == 1 ? "Www" : log.LogSourceId == 2 ? "Intranet" : "EmailNotification",
LogText = log.LogText
});
如您所见,此查询将确定对象的属性。该示例来自日志表,但它可以来自任意数量的表。然后,如果我想从原始帖子中调用通用搜索方法:
query = DataTableHelper.SearchAllFields(query, pageRequest.Search);
答案 0 :(得分:2)
您可以使用反射来搜索元素的所有属性,但是如果要返回任何属性匹配的所有行,则需要使用谓词构建器来构建应用的查询而不是Where()。
此示例代码将返回Foo的两个实例,其中A,B和C为“a”。 Bar的实例,其中E,F和G是“a”。还添加了匿名类型的示例。
class Program
{
private class Foo
{
public string A { get; set; }
public string B { get; set; }
public string C { get; set; }
}
private class Bar
{
public string E { get; set; }
public string F { get; set; }
public string G { get; set; }
}
static void Main(string[] args)
{
var list = new List<Foo>
{
new Foo { A = "a", B = "a", C = "a" },
new Foo { A = "a2", B = "b2", C = "c2" },
new Foo { A = "a3", B = "b3", C = "c3" },
};
var list2 = new List<Bar>
{
new Bar { E = "a", F = "a", G = "a" },
new Bar { E = "a2", F = "b2", G = "c2" },
new Bar { E = "a3", F = "b3", G = "c3" },
};
var q1 = Filter(list.AsQueryable(), "a");
var q2 = Filter(list2.AsQueryable(), "a");
foreach (var x in q1)
{
Console.WriteLine(x);
}
foreach (var x in q2)
{
Console.WriteLine(x);
}
var queryable = list.Select(p => new
{
X = p.A,
Y = p.B,
Z = p.C
}).AsQueryable();
var q3 = Filter(queryable, "a");
foreach (var x in q3)
{
Console.WriteLine(x);
}
Console.ReadKey();
}
private static IQueryable<object> Filter(IQueryable<object> list, string value)
{
foreach (var prop in list.ElementType.GetProperties())
{
var prop1 = prop;
list = list.Where(l => Equals(prop1.GetValue(l, null), value));
}
return list;
}
}