2012-06-02 51 views
1

考慮一個簡單的Employee類。從參數構建LINQ查詢

Class Employee 
{ 
    public String FirstName {get; set;} 
    public int Id {get; set;} 
    public int Marks {get; set;} 
    public String LastName {get; set;} 
} 

因此,對於通過LINQ查詢進行選擇,我們可以編寫。

var query = Employee.Where(i => i.Id > 2).OrderBy(i => i.Marks); 

所以我們可以創建一個函數,它需要2個參數,我們可以發送Id和Marks。 因此,我可以做一個函數調用並傳遞參數,我需要什麼。

var query = Employee.Where(i => i.Marks > 2).OrderBy(i => i.FirstName); 

樣品尋找功能,我們可以通過任何參數

Public String GetQuery(String para1,String para2,......) 
{ 
    var query = Employee.Where(i => i.para1 > 2).OrderBy(i => i.para2); 
    return query; 
} 
    or 

Public String GetQuery(String para1,String para2,......) 
{ 
    String str1=para1...... // with some format included 
    String str2=para2...... // with some format included 

    var query = Employee.Where(str1).OrderBy(str2); 
    return query; 
} 

的概念是,我想創建一個公共(通用)的查詢中,我可以選擇的值傳遞任何類型的參數的 。

+0

因此..你想採取一種乾淨的,可組合的,強類型的方法,並把它變成一個弱的,不可組合的,基於字符串的方法......爲什麼? –

+0

不完全我只是想要一個泛型類型。喜歡假設我想要獲得一個按列名稱的行,所以在參數我可以傳遞上下文和列,並獲得所需的值 – Padmalochan

+0

它是如何知道該列是什麼類型或什麼樣的比較表達式,你想對它做... .. 。?你最好直接編寫一個LINQ表達式,因爲調用者知道字段,類型和比較。 –

回答

0

A型安全的解決方案可以使用委託,而不是字符串:

IEnumerable<Employee> employees = getExampleData(); 

IEnumerable<Employee> example1 = Query.Employees(employees, Query.UseID, Query.UseMarks); 
IEnumerable<Employee> example2 = Query.Employees(employees, Query.UseMarks, Query.UseFirstName); 

我做了一個輔助類查詢包裹功能:

static class Query 
{ 
    public static int UseID(Employee employee, int i) { return employee.Id; } 
    public static int UseMarks(Employee employee, int i) { return employee.Marks; } 
    public static string UseFirstName(Employee employee, string s) { return employee.FirstName; } 
    public static string UseLastName(Employee employee, string s) { return employee.LastName; } 

    static public IEnumerable<Employee> Employees(IEnumerable<Employee> employees, func_returnInt where, func_returnInt orderby) 
    { 
     return employees.Where(i => where(i, 0) > 2).OrderBy(i => orderby(i, 0)); 
    } 
    static public IEnumerable<Employee> Employees(IEnumerable<Employee> employees, func_returnInt where, func_returnString orderby) 
    { 
     return employees.Where(i => where(i, 0) > 2).OrderBy(i => orderby(i, "")); 
    } 
} 

public delegate int func_returnInt(Employee employee, int i); 
public delegate string func_returnString(Employee employee, string s); 
0

你必須使用表達式:LambdaExpression。

http://msdn.microsoft.com/en-us/library/bb335710.aspx

在我的代碼我已經使用類似的東西:

private User GetUser(Expression<Func<User, bool>> query) 
{ 
    User user = context.Users.Where(query).FirstOrDefault(); 
    if (user == null) 
    { 
     throw new ProviderException("The supplied user name could not be found."); 
    } 
    return user; 
} 

用戶的用戶=的getUser(U => u.Marks == 123);

User user = GetUser(u => u.FirstName ==「abc」);