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. atitit.mp4 视频文件多媒体格式结构详解

    atitit.mp4 视频文件多媒体格式结构详解 1. 一.基本概念1 2. MP4文件概述2 3. mp4是由一个个“box”组成的,2 4. 典型简化mp43 5. Fragments5 6. r ...

  2. Atitit.病毒木马程序的感染 传播扩散 原理

    Atitit.病毒木马程序的感染 传播扩散 原理 1. 从木马的发展史考虑,木马可以分为四代 1 2. 木马有两大类,远程控制  vs  自我复制传播1 3. 自我复制2 3.1. 需要知道当前cpu ...

  3. JAVA基础学习day19--IO流一、FileWrite与FileReader

    一.IO简述 1.1.简述 IO:input/output IO流用来处理设备之间的数据传输 Java对数据的操作是通过流的方式 Java用于操作流的对象都在IO包中. 1.2.结构 字节流抽象类: ...

  4. ListView嵌套出现的问题

    项目中一个列表子项中也需要用到列表,这就不由得使我想到ListView的嵌套,其实这个东西想想也只是复杂了一点,并没有什么难的地方,可是却依然在这里狠狠滴栽个跟头.问题出在子列表动态展开的操作上.可能 ...

  5. iOS开发笔记10:圆点缩放动画、强制更新、远程推送加语音提醒及UIView截屏

    1.使用CAReplicatorLayer制作等待动画 CALayer+CABasicAnimation可以制作很多简单的动画效果,之前的博客中介绍的“两个动画”,一个是利用一张渐变色图片+CABas ...

  6. Android Design Support Library——TabLayout

    TabLayout——选项卡布局,通过选项卡的方式切换view并不是material design中才有的新概念,选项卡既可以固定,也可以滚动显示效果如下: 通过addTab方法可以实现选项卡的动态添 ...

  7. Mysql的float类型造成的困扰总结

    因为换了工作正在学习使用MySQL,今天领导提出了一个问题,如下: X列是累加值,A列是每日新增值,那么X2应该是X1+A2,而且存储过程里也是这样计算的.可是奇怪的是X2的值却总是和正确值(2396 ...

  8. jQuery form插件的使用--使用 fieldValue 方法校验表单

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <hea ...

  9. 仅IE6/7中添加checked为true的input到DOM中为false

    HTML INPUT元素有个checked属性,多数情况type为radio和checkbox. 当创建一个input,checked属性赋值为true,添加到DOM文档中,当再次取checked属性 ...

  10. python 解析json loads dumps

    认识 引用模块 重要函数 案例 排序 缩进参数 压缩 参考 认识 JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式.它基于JavaScript(Standa ...