C# 如何使用动态字符串过滤带有字符串的字段X?
大概是这样的:C# 如何使用动态字符串过滤带有字符串的字段X?,c#,linq,entity-framework,C#,Linq,Entity Framework,大概是这样的: public static class ExtensionMethods { public static IQueryable<MovieList> FilterEntityCollection(this IQueryable<MovieList> movies, IEnumerable<Foo.Models.FilterCriteria> filters) { foreach (var filter in fi
public static class ExtensionMethods
{
public static IQueryable<MovieList> FilterEntityCollection(this IQueryable<MovieList> movies, IEnumerable<Foo.Models.FilterCriteria> filters)
{
foreach (var filter in filters)
{
// Apply the filter to the collection.
movies= movies.Where(x => x.filter.FieldName == filter.expr);
//x."MovieTitle" == "Jaws"
}
return movies;
}
}
公共静态类扩展方法
{
公共静态IQueryable筛选器EntertyCollection(此IQueryable电影,IEnumerable筛选器)
{
foreach(过滤器中的var过滤器)
{
//将筛选器应用于集合。
movies=movies.Where(x=>x.filter.FieldName==filter.expr);
//x、 “MovieTitle”=“Jaws”
}
返回电影;
}
}
像这样的事情可以在C#中完成吗?使用
有点像:
var predicate = PredicateBuilder.True<MovieList>();
foreach (var filter in filters)
{
string filter1 = filter;
predicate = predicate.And(a => a.filter.FieldName == filter1);
}
return movies.AsExpandable().Where(predicate);
var predicate=PredicateBuilder.True();
foreach(过滤器中的var过滤器)
{
字符串过滤器1=过滤器;
谓词=谓词和(a=>a.filter.FieldName==filter1);
}
返回movies.AsExpandable().Where(谓词);
LinqKit谓词生成器
using System;
using System.Linq.Expressions;
using System.Runtime.CompilerServices;
namespace LinqKit
{
public static class PredicateBuilder
{
public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2);
public static Expression<Func<T, bool>> False<T>();
public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2);
public static Expression<Func<T, bool>> True<T>();
}
}
使用系统;
使用System.Linq.Expressions;
使用System.Runtime.CompilerServices;
名称空间LinqKit
{
公共静态类谓词生成器
{
公共静态表达式和(此表达式expr1,表达式expr2);
公共静态表达式False();
公共静态表达式或(此表达式expr1,表达式expr2);
公共静态表达式True();
}
}
您可以使用反射,以获得所需的灵活性。既然这是昂贵的,我想问题是你用什么来坚持这部电影?它有任何查询功能吗?数据保存在MSSQL数据库中。那么第一条注释中的链接应该会有所帮助。该查询将在SQL引擎中进行,而不是在内存中进行,就像我在给定代码时假设的那样。它是关于将字符串值转换为表达式。