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. MSCRM 迁移 数据库 服务器

    Move the Microsoft Dynamics CRM databases to another SQL Server and SQL Server Reporting Services se ...

  2. 解决C#导出excel异常来自 HRESULT:0x800A03EC的方法 .

    解决C#导出excel异常来自 HRESULT:0x800A03EC的方法 .   xlBook.SaveAs(FilePath,Microsoft.Office.Interop.Excel.XlFi ...

  3. Android系统提供的开发常用的包名及作用

    android.app :提供高层的程序模型.提供基本的运行环境 android.content :包含各种的对设备上的数据进行访问和发布的类 android.database :通过内容提供者浏览和 ...

  4. 实战1--应用EL表达式访问JavaBean的属性

    (1)编写index.jsp页面,用来收集用户的注册信息 <%@ page language="java" pageEncoding="GBK"%> ...

  5. 使用VideoView自定义一个播放器控件

    介绍 最近要使用播放器做一个简单的视频播放功能,开始学习VideoView,在横竖屏切换的时候碰到了点麻烦,不过在查阅资料后总算是解决了.在写VideoView播放视频时候定义控制的代码全写在Actv ...

  6. iOS 在制作framework时候对aggregate的配置

    # Sets the target folders and the final framework product.# 如果工程名称和Framework的Target名称不一样的话,要自定义FMKNA ...

  7. Swift Standard Library: Documented and undocumented built-in functions in the Swift standard library – the complete list with all 74 functions

    Swift has 74 built-in functions but only seven of them are documented in the Swift book (“The Swift ...

  8. 【mysql】关于checkpoint机制

    一.简介 思考一下这个场景:如果重做日志可以无限地增大,同时缓冲池也足够大,那么是不需要将缓冲池中页的新版本刷新回磁盘.因为当发生宕机时,完全可以通过重做日志来恢复整个数据库系统中的数据到宕机发生的时 ...

  9. 基于WF4.0的公文管理系统

    系统功能说明 公文管理 通过定义公文的基本信息,并将它按照工作流的定义流转实现公文的管理.包含以下功能: )公文创建:用户能够将格式化文本作为公文上传到系统中,并选择工作流启动流程. )公文审批:具有 ...

  10. html列表

    有序列表 <ol type="A", start="C"> <!--ordered list--> <li>第一项</ ...