如何使用动态字符串过滤字符串X?

如何使用动态字符串过滤字符串X?

问题描述:

事情是这样的:如何使用动态字符串过滤字符串X?

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; 
    } 
} 

能像这样在C#中做什么?

+1

的可能重复 - (http://stackoverflow.com/ [LINQ动态WHERE子句?] questions/848415/linq-dynamic-where-clause) – 2013-04-11 20:52:36

+0

您可以使用反射来寻找所需的灵活性。 既然这样很贵,我想问题是你用什么来坚持这些电影?它有没有任何查询功能? – 2013-04-11 20:52:37

+0

数据保存在MSSQL数据库中。 – sergserg 2013-04-11 20:53:54

使用LinqKit

有点像:

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); 

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>(); 
    } 
} 
+0

这是关于将字符串值转换为表达式。 – 2013-04-11 20:54:31