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. SharePoint 2013 跨网站集发布功能简介

    在SharePoint Server 2013网站实施中,我们经常会遇到跨网站集获取数据,而2013的这一跨网站集发布功能,正好满足我们这样的需求. 使用SharePoint 2013中的跨网站发布, ...

  2. IO流-输入输出

    java的I/O技术可以将数据保存到文本.二进制.ZIP压缩文件中,下面来说说一些基本的常识(今天只讲理论).先来说说流,何为流?“流就是一组有序的数据序列,根据操作的类型,可以分为输入(Input) ...

  3. 安卓开发_浅谈SubMenu(子菜单)

    子菜单,即点击菜单后出现一个菜单栏供选择 创建子菜单的步骤: (1) 覆盖Activity的onCreateOptionsMenu()方法,调用Menu的addSubMenu()方法来添加子菜单 (2 ...

  4. [leetcode] Contains Duplicate

    Contains Duplicate Given an array of integers, find if the array contains any duplicates. Your funct ...

  5. nutch简介

    1.什么是 nutch Nutch 是一个开源的. Java 实现的搜索引擎.它提供了我们运行自己的搜 索引擎所需的全部工具.2.研究 nutch 的原因(1) 透明度: nutch 是开放源代码的, ...

  6. 【转载】iOS堆和栈的理解

    操作系统iOS 中应用程序使用的计算机内存不是统一分配空间,运行代码使用的空间在三个不同的内存区域,分成三个段:“text segment “,“stack segment ”,“heap segme ...

  7. CocoaPods的使用(图文并茂)OS X 10.11 系统

    系统:OS X EI Capitan 版本:10.11.2 开发工具:XCode:7.2 要使用CocoaPods,那么就需要先安装哦,你安装了么?如果没安装那就请阅读我的前篇<OS X 10. ...

  8. MaxMin搜索

  9. Linux Shell 05 位置变量(命令行参数)

    在Linux shell 脚本中可能会用到一些命令行参数,常见如下: $0:脚本名称 $#:执行脚本时传入的参数个数,不包括脚本名称 $@:所有参数 $*:所有参数 $1...$9:第1个参数.... ...

  10. 问题解决——使用串口调试助手发送控制字符 协议指令 <ESC>!?

    外行指挥内行的结果就是,你必须按照他想的去做,等做不出来再用自己的办法,而且必须如此. -------------------------------------------------------- ...