1.Expression<Func<T,TResult>>是表达式

//使用LambdaExpression构建表达式树
Expression<Func<int, int, int, int>> expr = (x, y, z) => (x + y) / z;
Console.WriteLine(expr.Compile()(, , ));

https://msdn.microsoft.com/zh-cn/library/system.linq.expressions.expression(v=vs.100).aspx

https://msdn.microsoft.com/zh-cn/library/bb335710(v=vs.100).aspx

2.Func<T, TResult> 委托

封装一个具有一个参数并返回 TResult 参数指定的类型值的方法。
public delegate TResult Func<in T, out TResult>(T arg)
类型参数
in T
此委托封装的方法的参数类型。
该类型参数是逆变的。即可以使用指定的类型或派生程度更低的类型。有关协变和逆变的更多信息,请参见泛型中的协变和逆变。
out TResult
此委托封装的方法的返回值类型。
该类型参数是协变的。即可以使用指定的类型或派生程度更高的类型。有关协变和逆变的更多信息,请参见泛型中的协变和逆变。
参数
arg
类型:T
此委托封装的方法的参数。
返回值
类型:TResult
此委托封装的方法的返回值。

  string mid = ",middle part,";
///匿名写法
Func<string, string> anonDel = delegate(string param)
{
param += mid;
param += " And this was added to the string.";
return param;
};
///λ表达式写法
Func<string, string> lambda = param =>
{
param += mid;
param += " And this was added to the string.";
return param;
};
///λ表达式写法(整形)
Func<int, int> lambdaint = paramint =>
{
paramint = ;
return paramint;
};
///λ表达式带有两个参数的写法
Func<int, int, int> twoParams = (x, y) =>
{
return x*y;
};
MessageBox.Show("匿名方法:"+anonDel("Start of string"));
MessageBox.Show("λ表达式写法:" + lambda("Lambda expression"));
MessageBox.Show("λ表达式写法(整形):" + lambdaint().ToString());
MessageBox.Show("λ表达式带有两个参数:" + twoParams(, ).ToString());

来自:

http://blog.csdn.net/shuyizhi/article/details/6598013

3.使用Expression进行查询拼接

    public static class DynamicLinqExpressions
{ public static Expression<Func<T, bool>> True<T>() { return f => true; }
public static Expression<Func<T, bool>> False<T>() { return f => false; } 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);
} 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);
} }

使用方法

       public static IEnumerable<T> FilterBy<T>(this IEnumerable<T> collection, IEnumerable<KeyValuePair<string, string>> query)
{
var filtersCount = int.Parse(query.SingleOrDefault(k => k.Key.Contains("filterscount")).Value); Expression<Func<T, bool>> finalquery = null; for (var i = ; i < filtersCount; i += )
{
var filterValue = query.SingleOrDefault(k => k.Key.Contains("filtervalue" + i)).Value;
var filterCondition = query.SingleOrDefault(k => k.Key.Contains("filtercondition" + i)).Value;
var filterDataField = query.SingleOrDefault(k => k.Key.Contains("filterdatafield" + i)).Value;
var filterOperator = query.SingleOrDefault(k => k.Key.Contains("filteroperator" + i)).Value; Expression<Func<T, bool>> current = n => GetQueryCondition(n, filterCondition, filterDataField, filterValue); if (finalquery == null)
{
finalquery = current;
}
else if (filterOperator == "")
{
finalquery = finalquery.Or(current);
}
else
{
finalquery = finalquery.And(current);
}
}; if (finalquery != null)
collection = collection.AsQueryable().Where(finalquery); return collection;
}

要使用AsQueryable,必须引入 LinqKit.EntityFramework;如果不使用AsQueryable将会报错。

4.关于SelectListItem的扩展

using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Web.Mvc;
using System.Web.UI; namespace Web.Helper
{
public static class SelectListItemExtensions
{
/// <summary>
/// Data.ToSelectListItems(s=>s.Id,s=>s.Name);
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="baseEntities"></param>
/// <param name="valueExpression"></param>
/// <param name="textExpression"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
public static IEnumerable<SelectListItem> ToSelectListItems<T>(this IEnumerable<T> baseEntities, Expression<Func<T, string>> valueExpression, Expression<Func<T, string>> textExpression, object defaultValue = null)
{
dynamic valueNameObject = valueExpression.Body.GetType().GetProperty("Member").GetValue(valueExpression.Body, null);
dynamic textNameobject = textExpression.Body.GetType().GetProperty("Member").GetValue(textExpression.Body, null); var valueName = (string)valueNameObject.Name;
var textName = (string)textNameobject.Name; return ToSelectListItems(baseEntities, valueName, textName, null);
}
/// <summary>
/// Data.ToSelectListItems("Id", "Name")
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="baseEntities"></param>
/// <param name="valueName"></param>
/// <param name="textName"></param>
/// <param name="defaultValue"></param>
/// <returns></returns>
public static IEnumerable<SelectListItem> ToSelectListItems<T>(this IEnumerable<T> baseEntities, string valueName, string textName, object defaultValue = null)
{
if (string.IsNullOrWhiteSpace(valueName) || string.IsNullOrWhiteSpace(textName))
{
return new List<SelectListItem>();
}
var selectListItem = new List<SelectListItem>();
if (defaultValue != null)
{
foreach (var baseEntity in baseEntities)
{
var itemValue = GetPropertyValue(baseEntity, valueName);
selectListItem.Add(new SelectListItem()
{
Value = itemValue.ToString(),
Text = GetPropertyValue(baseEntity, textName).ToString(),
Selected = itemValue == defaultValue
});
}
}
else
{
foreach (var baseEntity in baseEntities)
{
selectListItem.Add(new SelectListItem()
{
Value = GetPropertyValue(baseEntity, valueName).ToString(),
Text = GetPropertyValue(baseEntity, textName).ToString(),
});
}
} return selectListItem;
} public static object GetPropertyValue(object obj, string propertyName)
{
//反射去获得对象的某个属性值
//Type t = obj.GetType();
//PropertyInfo info = t.GetProperty(propertyName);
//return info.GetValue(obj, null); //设置为SetValue return DataBinder.GetPropertyValue(obj, propertyName);
//return DataBinder.Eval(obj, propertyName);
} }
}

原文:http://blog.csdn.net/nabila/article/details/8137169

Expression<Func<T,TResult>>和Func<T,TResult>的更多相关文章

  1. Expression<Func<T,TResult>>和Func<T,TResult> 与AOP与WCF

    1>>Expression<Func<T,TResult>>和Func<T,TResult>http://www.cnblogs.com/xcsn/p/ ...

  2. Expression<Func<TObject, bool>>与Func<TObject, bool>的区别

    Func<TObject, bool>是委托(delegate) Expression<Func<TObject, bool>>是表达式 Expression编译后 ...

  3. lambda表达式Expression<Func<Person, bool>> 、Func<Person, bool>区别

    前言: 自己通过lambda表达式的封装,将对应的表达式转成字符串的过程中,对lambda表达式有了新的认识 原因: 很多开发者对lambda表达式Expression<Func<Pers ...

  4. Expression<Func<T, bool>>与Func<T, bool>的区别

    转自:http://www.cnblogs.com/wow-xc/articles/4952233.html Func<TObject, bool>是委托(delegate) Expres ...

  5. EF Core 封装方法Expression<Func<TObject, bool>>与Func<TObject, bool>区别

    unc<TObject, bool>是委托(delegate) Expression<Func<TObject, bool>>是表达式 Expression编译后就 ...

  6. expression<Func<object,Bool>> 及 Func<oject,bool>用法

    using System;using System.Collections.Generic;using System.Linq;using System.Linq.Expressions;using ...

  7. 从var func=function 和 function func()区别谈Javascript的预解析机制

    var func=function 和 function func()在意义上没有任何不同,但其解释优先级不同:后者会先于同一语句级的其他语句. 即: { var k = xx(); function ...

  8. onclick="func()"和 onclick = "return func()"区别

    onclick="func()" 表示只会执行 func , 但是不会传回 func 中之回传值onclick = "return func()" 则是 执行 ...

  9. 【转】int const A::func()和int A::func() const

    int const A::func() { return 0; }int A::func() const { return 0; } 上面的代码是合法的,其中A::func成员函数[只能在成员函数后面 ...

随机推荐

  1. [Microsoft Dynamics CRM 2016]Invalid Action – The selected action was not valid 错误的诱因及解决方法

    详细问题描述: 由于解决windows server 评估版过期\SQL server 评估版过期的问题后而导致的Invalid Action – The selected action was no ...

  2. OC 复合 组装电脑

    键盘类 #import <Foundation/Foundation.h> @interface Keyboard : NSObject @property(strong,nonatomi ...

  3. Android常用设计模式(一)

    java有23中设计模式,Android中也用到了很多的设计模式,本篇就来介绍Android中常用的几种设计模式 一.普通工厂设计模式 普通工厂设计模式,就是创建一个工厂类负责创建对象 ,用户根据需求 ...

  4. iOS之 PJSIP静态库编译(二)

    咱们书接上回: 上一篇编译好了PJsip这次我们来点实战 上次编译过后就不必做别的修改因为ios平台的库都支持了. 打开工程   找到 pjsip- apps/src/pjsua/ios/ipjsua ...

  5. 8 Regular Expressions You Should Know

    Regular expressions are a language of their own. When you learn a new programming language, they're ...

  6. Burp Suite安装及详细使用教程-Intruder模块详解

    01 介绍 安装要求: Java 的V1.5 + 安装( 推荐使用最新的JRE ), 可从这里免费 http://java.sun.com/j2se/downloads.html Burp Suite ...

  7. LINQ SQL分组取最近一条记录

    最近项目有一个需求,从订单表查询出每个客户最近一条订单记录.数据库表结构如下图 SELECT * FROM ( select ROW_NUMBER()over(partition by [custid ...

  8. 【重构】 利用 cos 组件实现jsp中上传附件

    利用JSP&Servlet重构项目 利用 cos 组件实现jsp中上传附件 fileUpload.jsp --> FileUploadController.java --> fil ...

  9. Hibernate之Criteria的完整用法

    Criteria的完整用法 QBE (Query By Example) Criteria cri = session.createCriteria(Student.class); cri.add(E ...

  10. JavaScript Patterns 4.5 Immediate Functions

    The immediate function pattern is a syntax that enables you to execute a function as soon as it is d ...