2015-12-04 70 views
2

我有一個允許用戶通過多個字段進行搜索的頁面。一個可以使用或全部使用。用戶可以設置每場運營商平等相待,包含,開頭爲,等等......貌似這個enter image description herec#Dynamic lambda中的Where子句

我使用EntityFrame工作,並使用蘭巴像這樣的檢索數據:

listOfPeople = adDB.People.Where(x => x.LastName.StartsWith(lastName) && x.FirstName.StartsWith(firstName)).OrderBy(x => x.LastName) 

問題:如何根據用戶提供的數據動態創建where子句?

+1

的可能的複製[C#LINQ動態選擇與所有類型的數據(http://stackoverflow.com/questions/31789229/c-sharp-linq-dynamic-select-with -all型的數據) – tdbeckett

回答

3

可以使用的東西沿着Func鍵工廠的線條要做到這一點,因爲在where子句接受一個Func鍵。

實施例:

public class Program 
{ 
    public static void Main(string[] args) 
    { 
     var people = new[] 
     { 
      new Person {FirstName = "Hello", LastName = "World"}, 
      new Person {FirstName = "Foo", LastName = "Bar"}, 
     }; 

     Console.WriteLine(people.Where(FuncFactory.GetFilterFunc<Person>(FilterType.Contains, x => x.FirstName, "ello")).Any()); 
     Console.WriteLine(people.Where(FuncFactory.GetFilterFunc<Person>(FilterType.Equals, x => x.FirstName, "ello")).Any()); 
     Console.WriteLine(people.Where(FuncFactory.GetFilterFunc<Person>(FilterType.Contains, x => x.LastName, "ar")).Any()); 
     Console.WriteLine(people.Where(FuncFactory.GetFilterFunc<Person>(FilterType.Equals, x => x.LastName, "ar")).Any()); 

     Console.ReadKey(); 
    } 
} 

public class Person 
{ 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
} 

public enum FilterType 
{ 
    Contains, 
    Equals 
} 

public static class FuncFactory 
{ 
    public static Func<T, bool> GetFilterFunc<T>(FilterType filterType, Func<T, IComparable> propFunc, string filter) 
    { 
     switch (filterType) 
     { 
      case FilterType.Contains: 
       return x => (propFunc(x) as string).Contains(filter); 
      case FilterType.Equals: 
       return x => (propFunc(x) as string).Equals(filter); 
      default: 
       throw new ArgumentException("Invalid FilterType"); 
     } 
    } 
}