0

我想将过滤器作为字符串参数传递。

public static List<Contact> Search(string filtre){
   var contacts =  bdContext.Contact.OrderBy( e => e.[filtre]).ToList();
   return contacts;
}

代码:

var contacts = bdContext.Contact.OrderBy(e.GetType().GetProperty(filter))
4

3 回答 3

0

您可以使用Nuget上提供的 Dynamic Linq 。您需要添加命名空间,System.Linq.Dynamic然后才能将字符串传递给OrderBy函数。

using System.Linq.Dynamic;
...
public static List<Contact> SearchDynamic(string filtre)
{
    var contacts = Contacts.OrderBy(filtre).ToList();
    return contacts;
}
...
Contacts = SearchDynamic("SomeProperty");

或者,您可以将 an 传递Expression<Func<Contact, T>>给您的搜索方法。这听起来比它更复杂:

//no need for Dynamic Linq here
public static List<Contact> Search<T>(Expression<Func<Contact, T>> filtre)
{
    var contacts = Contacts.OrderBy(filtre).ToList();
    return contacts;
}
...
Contacts = Search(c => c.SomeProperty);
于 2015-04-10T12:16:20.047 回答
0

如果要将过滤器作为参数传递并获取列表,则需要执行以下操作:

public static List<Contact> Search(string filtre){
   var contacts =  bdContext.Contact.where( e => e.columnname.Contains(filtre)).OrderBy(x=>x.ColumnName).ToList();
   return contacts;
}
于 2015-04-10T12:13:52.733 回答
0

您可以使用https://www.nuget.org/packages/System.Linq.Dynamic.Libraryhttps://www.nuget.org/packages/System.Linq.Dynamic/(它们是执行“动态" 基于字符串命令的查询。它们几乎是等价的,因为一个是另一个的分支)。

using System.Linq.Dynamic;

接着

var contacts = bdContext.Contact.OrderBy(filtre).ToList();

现在......如果您真的不想包含一个新库,您可以执行以下操作:

// We build the expression x => x.[filtre]
var parameter = Expression.Parameter(typeof(Contact));
var property = Expression.Property(parameter, filtre);
var expression = Expression.Lambda(property, parameter); // Returns a Expression<Func<Contact, typeof(propertyName)>>

// The "right" overload of OrderBy, in a "safe" way
var orderby = (from x in typeof(Queryable).GetMethods(BindingFlags.Static | BindingFlags.Public)
               where x.Name == "OrderBy" && x.IsGenericMethod
               let genericArguments = x.GetGenericArguments()
               let parameters = x.GetParameters()
               where genericArguments.Length == 2 && 
                   parameters.Length == 2 &&
                   parameters[0].ParameterType == typeof(IQueryable<>).MakeGenericType(genericArguments[0]) &&
                   parameters[1].ParameterType == typeof(Expression<>).MakeGenericType(typeof(Func<,>).MakeGenericType(genericArguments))
               select x).Single();

// We build from OrderBy<,> the OrderBy<Contact, typeof(filtre)>
orderby = orderby.MakeGenericMethod(typeof(Contact), expression.ReturnType);

// We invoke OrderBy<Contact, typeof(filtre)>
IQueryable<Contact> ordered = (IQueryable<Contact>)orderby.Invoke(null, new object[] { bdContext.Contact, expression });
var contacts = ordered.ToList();
于 2015-04-10T12:15:06.587 回答