研究linq 表达式的时候,遇到一篇不错的博客linq to sql,但是里边中有个知识点就是linq 拼接,最后认真分析才发现其中的Linq引用地方是内存地址,具体代码我粘贴如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
namespace LinqToString
{
public static class PredicateBuilder
{
/*lambel表达式中的True*/
public static Expression<Func<T, bool>> True<T>() {return f=>true; }
/*lambel表达式中的False*/
public static Expression<Func<T,bool>> False<T>(){return f=>false;}
/*lambel表达式中的OR*/
public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2)
{
var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
return Expression.Lambda<Func<T, bool>>(Expression.Or(expr1.Body, invokedExpr), expr1.Parameters);
}
/*lambel表达式中的And*/
public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expr1, Expression<Func<T, bool>> expr2)
{
var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
return Expression.Lambda<Func<T, bool>>(Expression.And(expr1.Body, invokedExpr), expr1.Parameters);
}
/*Expression<TDelegate>
以表达式树的形式将强类型 lambda 表达式表示为数据结构。此类不能被继承。
* Body表示表达式树的内容,Parameters表示表达式内的参数,ReturnType表示获取 lambda 表达式的返回类型。
*/
}
public class LinqMyCondition
{
IList<Student> strudents=new List<Student>
{
new Student(1,"j1",21,1),
new Student(2,"j2",26,3),
new Student(3,"j3",21,1),
new Student(4,"j4",27,4),
new Student(5,"j5",21,1),
new Student(6,"j6",21,2),
new Student(7,"j2",21,2)
};
public List<Student> GetStudentByOR(params string[] keywords)
{
IQueryable<Student> Istus = strudents.AsQueryable();
var predicate = PredicateBuilder.False<Student>();
foreach (string keyword in keywords)
{
string temp = keyword;//这个地方值得注意,确实注意引用地址
predicate = predicate.Or(p => p.sname.Contains(temp));
}
var query=Istus.Where(predicate).ToList();
return query;
}
public List<Student> ShowData(params string[] keywords)
{
IQueryable<Student> IQStudent = strudents.AsQueryable();
var predicat = PredicateBuilder.True<Student>();
// string temp = "";
foreach (string keyword in keywords)
{
string temp = keyword;
predicat = predicat.And(p => p.sname.Contains(temp));
//predicat = predicat.And(p => p.sname.Contains("1"));
//predicat = predicat.And(p => p.gid == 1);
}
var query = IQStudent.Where(predicat).ToList();
return query;
}
}
}