考虑一个简单的Employee类。
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)
类型安全的解决方案可以使用委托而不是字符串:
IEnumerable<Employee> employees = getExampleData();
IEnumerable<Employee> example1 = Query.Employees(employees, Query.UseID, Query.UseMarks);
IEnumerable<Employee> example2 = Query.Employees(employees, Query.UseMarks, Query.UseFirstName);
我创建了一个帮助类Query来包装功能:
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);
答案 1 :(得分:0)
您必须使用Expression: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;
}
用户user = GetUser(u =&gt; u.Marks == 123);
用户user = GetUser(u =&gt; u.FirstName ==“abc”);